Himanshu Jain
Himanshu Jain

Reputation: 13

Finding the bounding box around white background with white colour product in Python

enter image description hereI am trying to find the screen capture by the product in the image and form a bounded box using contour method using opencv, but there is low gradient difference in product color and background, I am not able to do this. Please tellenter image description here me how can I do this? Also, can I use any object detection method for this case?

Checkout the image here

Upvotes: 1

Views: 2045

Answers (1)

Piotr Siekański
Piotr Siekański

Reputation: 1715

See the snipped included. As your background is white you can find all pixels that are not white using inRange function, then find biggest contour from the remaining pixels and finally find the bounding rectangle of the biggest contour.

import numpy as np
import cv2
import imutils

image = cv2.imread(path) # path = path to your file
bin = cv2.inRange(image, (255, 255, 255), (255, 255,255))
cv2.bitwise_not(bin, bin)
cnts = cv2.findContours(bin.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)
rect = cv2.boundingRect(cnts[0])
cv2.rectangle(image, rect, (0,255,0), 1)

Result

Upvotes: 2

Related Questions