Jame H
Jame H

Reputation: 1384

Using opencv, how to remove non-object in transparent image?

I'm a newbie in image processing.

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

enter image description here

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.

Upvotes: 3

Views: 4049

Answers (1)

api55
api55

Reputation: 11420

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

UPDATE

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

Upvotes: 6

Related Questions