I'm trying to obtain the biggest yellow object in my image. I'm doing the following:
def findYellow(img):
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
lower_yellow, upper_yellow = np.array([18, 50, 90]), np.array([30, 255, 255])
mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
max_contour = max(contours, key = cv2.contourArea)
mask = np.zeros(img.shape[:2], dtype = 'uint8')
cv2.drawContours(mask, [max_contour], -1, (255), -1)
result = cv2.bitwise_and(img, img, mask=mask)
cv2.imwrite('result.png', result)
return result
Up to this point everything is correct.
But now I want to do the same but with transparent background (since now was black, mask = np.zeros()).
I understand that I have to work with the alpha channel, like mask = np.zeros((600,800, 4), dtype = 'uint8') but appears this error.
result = cv2.bitwise_and(img, img, mask=mask) cv2.error: OpenCV(3.4.2) C:\Miniconda3\conda-bld\opencv-suite_1534379934306\work\modules\core\src\arithm.cpp:241: error: (-215:Assertion failed) (mtype == 0 || mtype == 1) && _mask.sameSize(*psrc1) in function 'cv::binary_op'
Therefore my idea was to convert my current BGR image to BGRA like b = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA) but fails again with same error.
def findYellow(img):
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
lower_yellow, upper_yellow = np.array([18, 50, 90]), np.array([30, 255, 255])
mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
max_contour = max(contours, key = cv2.contourArea)
mask = np.zeros((600, 800, 4), dtype = 'uint8')
cv2.drawContours(mask, [max_contour], -1, (255), -1)
b = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
result = cv2.bitwise_and(b, b, mask=mask)
cv2.imwrite('result.png', result)
return result
Can somebody help me? I need to work with transparent background because in later steps black color affects me negatively.
Thank you very much!!