PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 27, 2022

[FIXED] What does cv2.approxPolydp() return?

 July 27, 2022     contour, crop, opencv, opencv-contour, python     No comments   

Issue

I am trying to resize an image according to the contour detected after applying cv2.approxPolyDP() . Afterwards, I have to custom crop it using cv2.resize() with dimensions for cropping according to the return values of the contour detected by the cv2.approxPolyDP().

I want to know which index is the height and which index is the width or the starting x,y coordinates and the ending x,y coordinates.

def biggestContour(contours):
    biggest = np.array([])
    max_area = 0
    for i in contours:
        area = cv2.contourArea(i)
        if area > 5000:
            peri = cv2.arcLength(i, True)
            approx = cv2.approxPolyDP(i, 0.02 * peri, True)
            if area > max_area and len(approx) == 4:
                biggest = approx
                max_area = area
    return biggest,max_area

Considering this code, how do I find which index is the height and which is the width or the starting x,y coordinates and the ending x,y coordinates?


Solution

cv2.approxPolyDP returns a resampled contour, so this will still return a set of (x, y) points. If you want to crop out this result, the returned contour should be a N x 1 x 2 NumPy array, so remove the singleton dimension, then do standard min/max operations on the x and y coordinates to get the top left and bottom right corners and finally crop. Assuming your image to crop is called img and your list of contours calculated from cv2.findContours is called contours, try:

# Find biggest contour
cnt, area = biggestContour(contours)

# Remove singleton dimensions
points = np.squeeze(cnt)

# Extract rows and columns
y = points[:, 0]
x = points[:, 1]

# Now crop
(topy, topx) = (np.min(y), np.min(x))
(bottomy, bottomx) = (np.max(y), np.max(x))
out = img[topy:bottomy+1, topx:bottomx+1]

out will now contain the cropped image.



Answered By - rayryeng
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing