Automatically cropping an image using Python

2024/10/14 17:23:26

I want to automatically crop an image using OpenCV into many images, the number of output images is variable. I started by replacing the white background by a transparent background.

The input image: enter image description here

I replace the white background by a transparent background using this script:

from PIL import Imageimg = Image.open('./images/SPORTS/546.png')
img = img.convert("RGBA")
datas = img.getdata()newData = []
for item in datas:if item[0] == 253 and item[1] == 252 and item[2] == 252:newData.append((255, 255, 255, 0))else:newData.append(item)img.putdata(newData)
img.show()
img.save("split_image_example.png", "PNG")

So in this example I want to get 4 separated images.

enter image description hereenter image description hereenter image description hereenter image description here

Answer

You can use BoundingRect() on findContour() See http://docs.opencv.org/2.4/doc/tutorials/imgproc/shapedescriptors/bounding_rects_circles/bounding_rects_circles.html

For your case :

img=cv2.imread(path_to_your_image,0)
if img is None:sys.exit("No input image") #good practice#thresholding your image to keep all but the background (I took a version of your
#image with a white background, you may have to adapt the threshold
thresh=cv2.threshold(img, 250, 255, cv2.THRESH_BINARY_INV);
res=thresh[1]#dilating the result to connect all small components in your image
kernel=cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
for i in range(10):res=cv2.dilate(res,kernel)#Finding the contoursimg2,contours,hierarchy=
cv2.findContours(res,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)cpt=0
for contour in contours:#finding the bounding rectangle of your contoursrect=cv2.boundingRect(contour)#cropping the image to the value of the bounding rectangleimg2=img[rect[1]:rect[1]+rect[3],rect[0]:rect[0]+rect[2]]cv2.imwrite("path_you_want_to_save"+str(cpt)+".png", img2)cpt=cpt+1;

This is a quick code, you may want to change : the saving method, the contour computing parameters, the dilatation method.... Most importantly, it suits the image you've given here but may not be appropriate for cases where your objects are closer by, or are more "sparse" (if dilating can't merge them together)

https://en.xdnf.cn/q/117928.html

Related Q&A

How to find highest product of k elements in an array of n length, where k n

I recently tried the question for the highest product of 3 elements. Now I am trying to do it for the k elements. Lets say from 3 now it is asking for 4 elements. I tried to write a generic function so…

Kivy error - Unable to get a window, abort

I installed kivy on my Raspberry pi3, where i run a python program that already works on another pi3.I now am trying to install the same thing on this second pi, and it doesnt work...maybe I forgot som…

Selenium 3.0.2 error with Firefox 50: executable may have wrong permissions

Im trying to use Selenium 3.0.2 with Firefox 50.0.1 in Windows 7. Ive followed the instructions in this post to setup correctly the driver and the paths but Im getting the following error: Traceback (m…

Convert a jpg to a list of lists

Im trying to figure out how to convert a jpg into a list of lists (using python 3.2.3) such that:[ [red,blue,red,etc..], #line1 [blue,red,yellow, etc...], #line2 [orange,yellow,black,et…

TypeError: No to_python (by-value) converter found for C++ type

Im trying to expose my C++ Classes to Python using Boost.Python. Here is a simplyfied version of what Im trying to do:struct Base {virtual ~Base() {};virtual char const *Hello() {printf("Base.Hell…

USB interface in Python

I have this (http://www.gesytec.de/en/download/easylon/p/16/) USB device connected to my Win7. I am just trying to read the vendor ID and product ID. I have Python 2.7.Here is the code,import usb busse…

Django M2M Through extra fields with multiple models

Im trying to figure out the best way to set up the following django model (genericised for security reasons).ThingA:User(M2M through "UserRelation")ThingB:User(M2M through "UserRelation&…

Openpyxl: Worksheet object has no attribute values

My goal is to read in an excel file and view the codes in a pandas dataframe (i.e. = A3) rather than the resulting values from excel executing the codes, which is the pandas default if read in using pa…

Calculation of Contact/Coordination number with Periodic Boundary Conditions

I have data for N atoms including the radius of each atom, the position of each atom and the box dimensions. I want to calculate the number of atoms each atom is in contact with and store the result. T…

how can I export multiple images using zipfile and urllib2

I am trying to add multiple image files into my zip. I have searched around and knows how to add a single one. I tried to loop through multiple images then write into it but it didnt work. I kind of d…