简体   繁体   English

如何使用opencv检测网格中的最大矩形?

[英]How to detect largest rectangle in a grid using opencv?

I have some images which are in form of a grid.我有一些网格形式的图像。 I have a code that works to find the largest rectangle in the grid.我有一个代码可以在网格中找到最大的矩形。 However it works in some images and completely fails in doing so in others, I need help fine-tuning the code to work in all the cases.然而,它在某些图像中有效而在其他图像中完全失败,我需要帮助微调代码以在所有情况下工作。 Ideally I'd like the contours exactly on the border.理想情况下,我希望轮廓恰好在边界上。

The code:编码:

import cv2
import numpy as np

img =  cv2.imread('3.jpg')
frame = cv2.resize(img,(1000,500))

hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_red = np.array([0, 10, 120])
upper_red = np.array([15, 255, 255])
mask = cv2.inRange (hsv, lower_red, upper_red)
cv2.imshow("a",mask)
cv2.waitKey(0)

contours, _ = cv2.findContours(mask.copy(),
                           cv2.RETR_TREE,
                           cv2.CHAIN_APPROX_SIMPLE)
if len(contours) > 0:
    red_area = max(contours, key=cv2.contourArea)
    x, y, w, h = cv2.boundingRect(red_area)
    cv2.rectangle(frame,(x, y),(x+w, y+h),(0, 0, 255), 2)

cv2.imshow('frame', frame)
cv2.imshow('mask', mask)

cv2.waitKey(0)

Image in which it works correctly:它正常工作的图像:

原图

边缘

检测到的矩形

Image in which the code does not work:代码不起作用的图像:

原来的

边缘

检测到的矩形

your problem in finding the max contour after thresolding can be solved simply by identifying the max contour corners:您可以通过识别最大轮廓角来解决阈值后找到最大轮廓的问题:

解决方案

import cv2
import numpy as np

img =  cv2.imread('2.png')
frame = cv2.resize(img,(1000,500))

hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_red = np.array([0, 10, 120])
upper_red = np.array([15, 255, 255])
mask = cv2.inRange (hsv, lower_red, upper_red)


y0 = np.min(np.where(mask>0)[0])
x0 = np.min(np.where(mask>0)[1])

y1 = np.max(np.where(mask>0)[0])
x1 = np.max(np.where(mask>0)[1])

cv2.rectangle(frame,(x0, y0),(x1, y1),(0, 0, 255), 2)

cv2.imshow('frame', frame)
cv2.imshow('mask', mask)

cv2.waitKey(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM