I'm a newbie in image processing.
I'm trying to resize the rectangle/frame bound my object in transparent image.

But i don't know how to make it.
Please help me.
Thank a lot. P/s: It doesn't duplicate with crop. In crop you have fix a tuple (Crop from x, y, w, h). But in my picture, I don't know where to crop. We need to detect minimize rectangle that contain my object(sunglass) first and crop then.
First you have to load the image with alpha support in OpenCV
import cv2
import numpy as np #needed in the second step
im = cv2.imread("image.png", cv2.IMREAD_UNCHANGED)
Notice the cv2.IMREAD_UNCHANGED, this is equal to -1. This will load an image with the format BGRA
Then you find the bounding rect of the object
# axis 0 is the row(y) and axis(x) 1 is the column
y,x = im[:,:,3].nonzero() # get the nonzero alpha coordinates
minx = np.min(x)
miny = np.min(y)
maxx = np.max(x)
maxy = np.max(y)
Then you crop the object
cropImg = im[miny:maxy, minx:maxx]
Finally you show and save your results to disk
cv2.imwrite("cropped.png", cropImg)
cv2.imshow("cropped", cropImg)
cv2.waitKey(0)
I have no time to test this code, so I may have a typo. I hope it helps you. Any problems, just comment this answer
Here is a small update to remove the extra white part:
First get a boolean mask where it is white
whiteCellsMask = np.logical_and(cropImg[:,:,0] == 255, np.logical_and(cropImg[:,:,1] == 255, cropImg[:,:,2]== 255))
Then change the alpha of the masked values to 0
cropImg[whiteCellsMask,:] = [255, 255, 255, 0]
This will change all the pixels which are white (255,255,255) to transparent (alpha = 0).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With