Opencv 找不到矩形形状

Opencv not finding rectangles shape

我正在尝试在此图像中找到矩形形状,但对我来说似乎太难了。我该怎么做才能完成它?

This is the image

Those are the rectangles im trying to find

我看到 2 个选项:

  • 如果您还没有找到矩形,请进入页面的html脚本,然后您会找到形状的尺寸

  • 如果您想在 python 中将其自动化,我认为您导入的是网站图片,而不是网站图片,因此,我知道的唯一解决方案是使用 AI代码,可以自己找到形状。在源代码中。我想您可以在网上轻松找到一些塑造矩形的 AI 的免费模型。这是打开的代码:

      import cv2 as cv
      img_new = cv.imread('file.jpg')
      cv.imwrite(filename='file.jpg')
      cv.imshow("Capturing")
      shape_cascade = cv.CascadeClassifier('TheAIModelPre-Trained.xml')
      img = cv.imread('file.jpg')
      gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
      shapes = shape_cascade.detectMultiScale(gray, 1.1, 8)
      i=0
      for shape in shapes : 
          x, y, w, h = shape
          cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
          shape = img[y:y+h, x:x+w]
          cv.imshow('shape{}'.format(i), shape)
          i += 1
      cv.imshow('main image', img)
      cv.waitKey(0)
      cv.destroyAllWindows()
    

HTH

如果这是一个网站,那么我会建议使用 selenium 或 requests 来抓取它并找到内容。

虽然如果你还是想用OpenCV来做的话,有一个比较复杂的方法来提取矩形。该过程将使用 cv2.inrange 函数首先识别并删除灰色区域,然后寻找轮廓和 select 具有相似大小的轮廓。虽然这不是通用方法并且不会在所有情况下都适用,但它应该足以满足您的特定用例。

代码如下所示:

import cv2
import numpy as np

image = cv2.imread("input.png")
image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# Found using a website like https://imagecolorpicker.com/
lowerThreshVals = (0, 0, 235)
upperThreshVals = (0, 0, 245)

thresh = cv2.inRange(image_hsv, lowerThreshVals, upperThreshVals)
thresh = cv2.bitwise_not(thresh)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:

    # Print the contour areas and find the appropriate range. Another approach here could be to look for the 4 contours with closest areas and use those.
    if 200000 > cv2.contourArea(cnt) > 180000:
        rect = cv2.minAreaRect(cnt)
        box = cv2.boxPoints(rect)
        box = np.int0(box)
        cv2.drawContours(image,[box],0,(0,0,255),2)
        
cv2.imwrite("output.png", image)

并且应该给你输出: