【问题标题】:How to find and draw largest rectangle inside contour area?如何在轮廓区域内找到并绘制最大的矩形?
【发布时间】:2019-08-19 23:17:12
【问题描述】:

我想使用特定像素比较图像

(score, diff) = compare_ssim(grayA[y:y+h, x:x+w], grayB[y:y+h, x:x+w], full=True)

但该函数仅支持矩形 ROI。我的投资回报率是一个轮廓。 为了比较,我需要轮廓内最大的矩形。如何找到轮廓区域内最大的矩形?

示例图片

【问题讨论】:

  • 投资回报率是什么意思?
  • 感兴趣区域。我拥有的轮廓,我定义为 ROI,如果我错了,对不起
  • 你能提供一些样品吗?
  • ibb.co/DkLQ7mr,在此链接中,

标签: python opencv boundary opencv-contour drawrectangle


【解决方案1】:

根据您的 OP,我建议使用 warpAffine 将 ROI 旋转为矩形,因为 ROI 已经是矩形但已旋转。这是一个简单的示例:

import cv2
import numpy as np

img = cv2.imread("1.png")
(H,W,c) = img.shape
print("shape = {},{}".format(H,W))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_,thresh = cv2.threshold(gray,128,255,cv2.THRESH_BINARY_INV)

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

res = np.zeros_like(img)
c = np.squeeze(contours[0])

# find rectangle's conner points
x = sorted(c, key=lambda a:a[0])
left = x[0]
right = x[-1]
y= sorted(c, key=lambda a:a[1])
top = y[0]
bottom = y[-1]

cv2.circle(img, (left[0],left[1]), 4, (0, 0, 255), -1)
cv2.circle(img, (right[0],right[1]), 4, (0, 0, 255), -1)
cv2.circle(img, (top[0],top[1]), 4, (0, 0, 255), -1)
cv2.circle(img, (bottom[0],bottom[1]), 4, (0, 0, 255), -1)

#calculate rectangle's shape
roi_w = int(np.sqrt((top[0]-right[0])*(top[0]-right[0])+(top[1]-right[1])*(top[1]-right[1])))
roi_h = int(np.sqrt((top[0]-left[0])*(top[0]-left[0])+(top[1]-left[1])*(top[1]-left[1])))

pts1 = np.float32([top,right,left])

# keep the top coords and calculate new coords for left and right
new_top = top
new_right = [top[0] + roi_w, top[1]]
new_left = [top[0], top[1] + roi_h]
pts2 = np.float32([new_top,new_right,new_left])

#rotate 
matrix = cv2.getAffineTransform(pts1, pts2)
result = cv2.warpAffine(img, matrix, (W,H))
cv2.drawContours(res, [contours[0]], 0, (0,255,0), 3)

# extract roi
roi = result[new_top[1]:new_left[1],new_top[0]:new_right[0]]

cv2.imshow("img",img)
cv2.imshow("result",result)
cv2.waitKey(0)

【讨论】:

  • 很好,很有帮助,谢谢。所以如果我想和非空停车场比较。如果我旋转图片会更好吗?
  • 是的,但这也可能取决于相机的视角。在此示例中,所有停车场都旋转了相同的角度,因此旋转很有用。但如果角度不同,这将不起作用。
猜你喜欢
  • 2016-09-19
  • 2020-04-15
  • 1970-01-01
  • 2021-09-01
  • 2018-02-13
  • 1970-01-01
  • 2013-12-03
  • 2021-09-07
  • 2012-02-03
相关资源
最近更新 更多