For a subject I am interested in as a hobby, I need to determine the corner coordinates of the display you see in the photo. I do not have theoretical knowledge about Python and computer vision, but I am trying to do it with the help of examples on the internet.
At my last point, it seems that I can detect the display on the computer, but I could not find the corner coordinates of the largest detected rectangle. The x,y,w,h values it gives me are very irrelevant.
Can you help me understand what the mistake is in the code I shared? Thanks in advance
`## get contour function
def getContours(img, imgContour):
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(imgContour, contours, -1, (255, 0, 255), 7)
maxArea = 0
maxContour = None
for cnt in contours:
area = cv2.contourArea(cnt)
print(f"Contour area: {area}")
if area > maxArea:
maxArea = area
maxContour = cnt
if maxContour is not None:
peri = cv2.arcLength(maxContour, True)
approx = cv2.approxPolyDP(maxContour, 0.02 * peri, True)
print(f"Number of approx vertices: {len(approx)}")
if len(approx) == 4 and maxArea > 100000: # Dikdörtgen olma ve alan kontrolü
x, y, w, h = cv2.boundingRect(approx)
cv2.drawContours(imgContour, [approx], -1, (0, 255, 0), 5)
return x, y, w, h
return None`
`## Infinite While loop
imgContour = img.copy()
imgBlur = cv2.GaussianBlur(img, (7, 7), 1)
imgGray = cv2.cvtColor(imgBlur, cv2.COLOR_BGR2GRAY)
threshold1 = cv2.getTrackbarPos("Threshold1", "Parameters")
threshold2 = cv2.getTrackbarPos("Threshold2", "Parameters")
imgCanny = cv2.Canny(imgGray, threshold1, threshold2)
kernel = np.ones((7, 7))
imgDil = cv2.dilate(imgCanny, kernel, iterations=1)
rect = getContours(imgDil, imgContour)
if rect:
x, y, w, h = rect # Boyut filtresi
print(f"Largest rectangle: x={x}, y={y}, w={w}, h={h}")
cv2.rectangle(imgContour, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(imgContour, f"x={x}, y={y}, w={w}, h={h}", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
else:
print("No rectangle found.")
`
(https://i.sstatic.net/3wpHcYlD.png)
I expect to get pixel values like (452,365), (1049,452), but the values I get are around x = 70, y = 70, w = 200, h = 103.
Ali Özgür Polat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.