Wednesday, April 1, 2020

Crop images using python OpenCV module

You could use photo editing application to crop images. But when you have 1000s of images to crop on the same size, you can also use the Python programming language to do the cropping automatically for you.

This will save a lot of time and manual effort as you will see below.

Here I have thousands of screenshot images where some parts need to be cropped out of the images. See the original and the final cropped image below;-

Original image

Cropped image

As you can see from the Original image above, we need to crop out the boxes in red color (that is: the header, thumbnail icons, and the follow button). We need only the text within the green box to get the final cropped image.

This is an easy task when using photo editing software such as GIMP or PhotoShop. I will take and average of 30 seconds to complete one of such cropping. But since we have thousands of images to crop, then it will take much more time to complete.

Let's use python to cut down the amount of time to accomplish similar task for thousands of images. Here I made use of the OpenCV module, you can also make use of other modules such as pillow module (a friendly fork of the Python Imaging Library (PIL)).

# import the needed modules...
import glob
import cv2

# Read all the screenshots in the folder
images = glob.glob(r'C:\Users\Yusuf_08039508010\Desktop\imgs\*png')
# len(images)

i = 0
for img in images:
    # read in each image from the loop...
    image = cv2.imread(img)
    # crop image by specifying startY:endY, startX:endX... origin starts from top left corner
    cropped = image[150:1900, 120:460]
    # save the image to disc...
    cv2.imwrite('Instagram__'+str(i)+".png", cropped)
    # print statement to show progress and increment i variable to make file name unique...
    print('Done for... ', i)
    i = i+1

That is it!

No comments:

Post a Comment