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