Issue
I am having an image as enclosed taken through a DSLR camera but its background is also seen on which the object is placed. I want to crop the object from the background. The image size is (3456,5184,3)
Sample image:
I tried a variety of solutions available ie., .using openCV methods like foreground extraction using grabcut, image thresholding and masking, edge detection with unsatisfactory results.
Please suggest the right approach.
Solution
Here's a method using thresholding + contour extraction
- Grayscale then Gaussian blur
- Otsu's threshold for binary image
- Dilate to connect into a single contour
- Extract ROI with numpy slicing
After converting to grayscale and Gaussian blurring, we Otsu's threshold
Now we have the desired foreground object in white, so we dilate to connect the contours to form a single contour
Finally we obtain the bounding box coordinates and extract the ROI
import cv2
# Grayscale, Blur, Otsu's threshold then dilate
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25,25))
dilate = cv2.dilate(thresh, kernel, iterations=3)
# Extract ROI
x,y,w,h = cv2.boundingRect(dilate)
ROI = image[y:y+h, x:x+w]
cv2.imshow('thresh', thresh)
cv2.imshow('dilate', dilate)
cv2.imshow('ROI', ROI)
cv2.waitKey()
Answered By - nathancy Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.