Bulk Object Detection and Cropping with DETR

bulk-object-detection-and-cropping-with-detr

Here is a link to my repo

The Python file, main.py, is an object detection application that uses the DEtection TRansformer (DETR) model from Facebook’s Hugging Face library. It allows users to identify and crop images of detected objects, storing these cropped images in a specified output directory.

The application provides a Graphical User Interface (GUI) developed with the tkinter library, where users can specify the input directory of images, the output directory for the cropped images, and a confidence level for the model to use in object detection.

Now, let’s break down the script into sections and explain each part in detail.

Importing Required Libraries

The script begins by importing the necessary libraries. These include:

  • tkinter: a standard Python interface to the Tk GUI toolkit, used for developing desktop applications.
  • filedialog: a tkinter module for displaying dialog boxes that let the user select files or directories.
  • PIL (Pillow): a library for opening, manipulating, and saving many different image file formats.
  • transformers: a state-of-the-art Natural Language Processing (NLP) library that provides pre-trained models for various tasks, including the DETR model used here for object detection.
  • torch: a Python library for scientific computing, especially deep learning, providing tensors that can run on either a CPU or a GPU.
  • requests and os: standard Python libraries for handling HTTP requests and interacting with the operating system, respectively.

Initializing the Model and Processor

The DetrImageProcessor and DetrForObjectDetection classes are imported from the transformers library. These are initialized with the pretrained DETR model from Facebook, "facebook/detr-resnet-50".

Defining the Image Crop Function

def image_crops(input_directory, output_directory, confidence):

    # Loop through every file in the input directory
    for filename in os.listdir(input_directory):
        # Get the path to the current file
        curr_path = os.path.join(input_directory, filename)

        # Open the current file as an image
        image = Image.open(curr_path)

        # Pass the image to the model to detect objects
        inputs = processor(images=image, return_tensors="pt")
        outputs = model(**inputs)

        # Get the dimensions of the image
        target_sizes = torch.tensor([image.size[::-1]])

        # Post process the model outputs to get the detected objects
        results = processor.post_process_object_detection(
            outputs, target_sizes=target_sizes, threshold=confidence)[0]

        # Loop through the detected objects
        with Image.open(curr_path) as im:
            for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
                # Round the coordinates of the detected object
                box = [round(i, 2) for i in box.tolist()]
                # Get the label of the detected object
                label_text = model.config.id2label[label.item()]
                print(
                    f"Detected {model.config.id2label[label.item()]} with confidence "
                    f"{round(score.item(), 3)} at location {box}"
                )

                # Create a directory for the label if it does not exist
                if not (os.path.exists(f"{output_directory}/{label_text}")):
                    os.mkdir(f"{output_directory}/{label_text}")
                counts[label_text] = counts.get(label_text, 0) + 1
                remote_region = im.crop(box)
                remote_region.save(
                    f"{output_directory}/{label_text}/{label_text}_{counts[label_text]}.jpg")

The image_crops function takes three arguments: input_directory, output_directory, and confidence. This function iterates through all the images in the input_directory, performs object detection on each image, and saves the cropped images in the corresponding output_directory. The confidence parameter is a threshold for the model to determine if an object is present or not.

The function performs the following steps:

  1. Loops through each image file in the input directory.
  2. Opens the image file and processes it using the DetrImageProcessor.
  3. Passes the processed image to the DetrForObjectDetection model.
  4. Gets the dimensions of the image and post-processes the model outputs to get the detected objects and their bounding boxes.
  5. Loops through each detected object and crops the image based on the bounding box coordinates.
  6. Saves the cropped image to the output directory, creating new directories for each detected object type if necessary.

GUI Functions

Several functions are defined to interact with the GUI:

  • select_input_dir: Lets the user choose the input directory.
  • select_output_dir: Lets the user choose the output directory.
  • submit: Gets the selected directories and confidence level, calls the image_crops function with these parameters, and closes the application after processing.

Building the GUI

The tkinter library is used to create the GUI. The application window is created using tk.Tk(). The GUI contains buttons for selecting the input and output directories, a slider for setting the confidence level, and a submit button to start the processing. The grid function is used to position these elements in the application window.

The mainloop function is called to start the tkinter event loop, which waits for user interaction and responds accordingly.

The final script is a complete application that allows users to perform object detection and image cropping tasks easily. It is a great example of how powerful machine learning models can be combined with user-friendly interfaces to create practical tools.

Some Examples

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
update-your-libraries-to-the-latest-version-with-yarn

Update your libraries to the latest version with yarn

Next Post
building-portfolio-with-next.js:-add-navbar,-footer,-and-metadata

Building Portfolio with Next.js: Add Navbar, Footer, and Metadata

Related Posts

「設計ミス」の社会を再編する:AIと共創する未来の働き方とシステム思考

こんにちは、Soraです。この記事をお読みいただき、ありがとうございます。突然ですが、少しだけ想像してみてください。朝、もう少しだけ布団の温もりを感じていたいのに、「仕事だから」と自分にムチを打って起き上がる。満員電車に身体を押し込まれ、会社に着けば成果を求められ、同僚のフォローに追われる。気づけば形式だけの会議が続き、帰宅する頃には自分のための時間はほとんど残っていない…。もし、こうした日々に少しでも心当たりがあるなら、ふと胸の奥で「このままで、本当にいいのだろうか?」という静かな声が聞こえることがあるのではないでしょうか。本稿では、その胸のざわめきを「個人の怠け」や「甘え」として片付けるのではなく、私たちを取り巻く社会そのものの「設計ミス」のシグナルとして捉え直すことを提案します。そして、その設計をどうすれば再編できるのか、具体的なデータも交えながら、皆さんと一緒に考えていきたいと思います。### 第一章|「労働=価値」という虚構の検証私たちはいつの間にか、「働くことが人間の価値を決める」という前提を内面化しています。しかし、この考え方は本当に自明なのでしょうか。いくつかのデータは、この前提が現代において大きな歪みを生んでいる可能性を示唆しています。 **異常に低い仕事への熱意:米ギャラップ社の調査によると、日本の「熱意あふれる社員」の割合はわずか5%。これは調査した139カ国中、最下位レベルです。多くの人が、仕事に対してポジティブな感情を持てずにいる現状が伺えます。* 構造的な高ストレス状態:厚生労働省の調査では、仕事で強いストレスを感じている労働者の割合は、常に半数を超えています。これは個人の精神的な強さの問題ではなく、労働環境そのものに構造的な問題が潜んでいることの現れです。* 先進国で低位の労働生産性:日本の時間当たり労働生産性は、OECD加盟38カ国中30位(2022年)と、長年低い水準にあります。長時間働き、高いストレスを感じているにもかかわらず、それが必ずしも高い成果に結びついていないのです。これらの事実は、「個人の努力が足りない」からではなく、「努力の方向性を規定する社会の設計そのもの」に無理が生じていることを示しているのではないでしょうか。### 第二章|人生を“準備期間”にしてしまうプログラム私たちの多くは、無意識のうちに次のような人生のレールに乗せられています。 **学生時代:より良い大学に入るための「準備」* 大学時代:より良い会社に入るための「準備」* 社会人時代:昇進や老後のための「準備」* 老後:人生の終わりを迎えるための「準備」人生が常に何かの「準備」の連続で、「今、この瞬間を生きる」ことが後回しにされてしまう。この構造を支えているのが、「安定こそが正義」「みんなと同じが安心」といった、思考停止を促す“プログラム”です。このプログラムは、私たちの感性を少しずつ麻痺させ、構造への疑問を抱かせないように作用します。**### 第三章|思考のOSを更新する「言語の再設計」社会のプログラムから抜け出し、自分自身の思考を取り戻す第一歩は、言葉を意識的に変えることです。固定観念を強化する言葉を、私は「毒語」と呼んでいます。この毒語を、本質を捉えた「対抗語彙」に置き換えることで、世界の見え方は大きく変わります。| 毒語(思考停止を招く言葉) | 対抗語彙(本質を捉える言葉) | 置き換えの狙い || :—…
Read More