[PYTHON] I tried trimming efficiently with OpenCV

It is said that pre-processing of teacher data is important when doing machine learning. And when recognizing an object by image processing, you want to trim only the object you want to learn to eliminate waste, right? However, it is also troublesome to trim and save using image editing software. So, this time, I will show you how to use OpenCV for efficient manual trimming.

What to do this time

The images in the directory are read in a batch, and the area you want to learn can be cropped one by one as shown below. The cropped image is stored in the storage directory. image.png

Selection of area to cut

First, use cv2.selectROI to get information on the x-axis, y-axis, height, and width, which is the origin of the selected area on the image by dragging and dropping, and the area selection screen will be displayed easily. After selecting the area to cut out, press the Enter key to get the coordinate information of the selected area as a tuple. (Pressing the C key cancels and returns (0.0. 0, 0))

selected = cv2.selectROI(img)

After acquiring the coordinate information of the selected area, you can cut out the image data.

imCrop = img[int(selected[1]):int(selected[1]+selected[3]),
                         int(selected[0]):int(selected[0]+selected[2])]

All you have to do is save the cut out image data.

cv2.imwrite(file_dir, imCrop)

Completed code

Here is the completed form including the code related to the file path operation. The path format is unified so that it can be used on Windows and UNIX.

trim_image.py



import cv2
import os
import sys

if __name__ == '__main__':
    args = sys.argv
    data_dir = args[1].replace('\\', '/')
    annotated_dir = data_dir + 'trimed'
    os.mkdir(annotated_dir)
    files = os.listdir(data_dir)
    img_files = [
        f for f in files if '.jpeg' in f or '.jpg' in f or '.png' in f]
    print(img_files)
    for img_file in img_files:
        # Read image
        img_dir = data_dir + img_file
        img = cv2.imread(img_dir)

        # Select ROI
        selected = cv2.selectROI(img)
        if sum(selected):
            # Crop image
            imCrop = img[int(selected[1]):int(selected[1]+selected[3]),
                         int(selected[0]):int(selected[0]+selected[2])]
            # write annotated img
            file_dir = annotated_dir + '/' + img_file
            cv2.imwrite(file_dir, imCrop)
            print('saved!')

With the following command, you can specify the path of the directory where the image data is saved and crop the images in the directory at once. The cropped image data is saved in the trimed directory created in the directory.

python trim_image.py path/to/img_dir

Recommended Posts

I tried trimming efficiently with OpenCV
I tried face recognition with OpenCV
I tried non-photorealistic rendering with Python + opencv
I tried "smoothing" the image with Python + OpenCV
I tried "differentiating" the image with Python + OpenCV
I tried to detect motion quickly with OpenCV
I tried "binarizing" the image with Python + OpenCV
I tried fp-growth with python
I tried Learning-to-Rank with Elasticsearch!
I tried clustering with PyCaret
I tried gRPC with Python
I tried scraping with python
I tried to extract features with SIFT of OpenCV
[OpenCV / Python] I tried image analysis of cells with OpenCV
I tried "morphology conversion" of images with Python + OpenCV
I tried "gamma correction" of the image with Python + OpenCV
I tried summarizing sentences with summpy
I tried machine learning with liblinear
I tried web scraping with python.
I tried moving food with SinGAN
I tried using GrabCut of OpenCV
I tried implementing DeepPose with PyTorch
I tried face detection with MTCNN
I tried running prolog with python 3.8.2.
I tried SMTP communication with Python
I tried sentence generation with GPT-2
I tried learning LightGBM with Yellowbrick
I tried to process the image in "sketch style" with OpenCV
I tried to process the image in "pencil style" with OpenCV
I tried to make an image similarity function with Python + OpenCV
I want to detect objects with OpenCV
OpenCV AI Kit (OAK-D) I tried @ windows10
I tried multiple regression analysis with polynomial regression
I tried sending an SMS with Twilio
I tried using Amazon SQS with django-celery
I tried to implement Autoencoder with TensorFlow
I tried linebot with flask (anaconda) + heroku
I tried to visualize AutoEncoder with TensorFlow
I tried to get started with Hy
I tried scraping Yahoo News with Python
I tried using Selenium with Headless chrome
I tried factor analysis with Titanic data!
I tried learning with Kaggle's Titanic (kaggle②)
I tried sending an email with python.
I tried a functional language with Python
I tried batch normalization with PyTorch (+ note)
I tried recursion with Python ② (Fibonacci sequence)
I tried implementing DeepPose with PyTorch PartⅡ
I tried to implement CVAE with PyTorch
I tried playing with the image with Pillow
I tried to solve TSP with QAOA
I tried simple image recognition with Jupyter
I tried CNN fine tuning with Resnet
I tried natural language processing with transformers.
#I tried something like Vlookup with Python # 2
I tried'Beauty'with OpenCV
I tried scraping
I tried PyQ
I tried AutoKeras
I tried papermill
I tried django-slack