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.
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.
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)
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