Hello,
I am currently building a solution to find a rectangle screen in a picture.
My workflow is:
- Load the image via cv2.loadImage
- Convert to grayscale
- Downscale the image for faster performance
- Run Canny Edge Detection on the image
- Find the contours of the edged image
- Loop over the individual contours, approximate the polygonal curve via approxPolyDP
- Find the polygonal curve with 4 polygons, and save it.
I am using opencv-python with the version 4.5.3.
This is my code:
contours, hierarchy = cv2.findContours(img_condensed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
print(contours)
img_contour = img_grey
plt.title("All Contours")
cv2.drawContours(img_contour, contours, -1, (0, 255, 0), 3)
plt.imshow(cv2.cvtColor(img_contour, cv2.COLOR_BGR2RGB))
plt.show()
# loop over contours
for (i, contour) in contours:
# Get length of contour
length = cv2.arcLength(contour, True)
# Approximates a polygonal curve with specified precision; Returns array with polygons
approx = cv2.approxPolyDP(contour, 0.015 * length, True)
# Duplicate img because of destructive drawContours function
img_contour = img_grey
plt.title("Individual Contour")
cv2.drawContours(img_contour, approx, -1, (0, 255, 0), 3)
plt.imshow(cv2.cvtColor(img_contour, cv2.COLOR_BGR2RGB))
plt.show()
# If the contour has 4 polygons, its our screen.
if len(approx) == 4:
# Save the screen
screenCnt = approx
# Stop searching
break
My problem is:
In the for loop the contour
variable holds all contours, not an individual one.
Here are test images of the entire contour versus the individual contours in the loop:
The picture above is shown for every single iteration.
Somehow I can’t iterate over single contours, but it is taking all contours all the time.
I think this is a versioning problem, I tried imutils grabcontours function before, but I get the same result.
Can anyone help me?