我想从带有一些噪声的灰度图像中获取矩形对象的角坐标。
我从这张图片开始https://imgur.com/BNoCn1u .中心区域有一个具有不同灰色强度的方格矩形。我想要的是绿色矩形的坐标 https://imgur.com/97efZlb .
使用以下代码:
im = cv2.imread("opencv_frame_0.tif",0)
data = np.array(im)
edg = cv2.Canny(data, 120, 255)
ret,thresh = cv2.threshold(data,140,255,1)
imshow(thresh,interpolation='none', cmap=cm.gray)
我能够得到 https://imgur.com/1xurVTB .看起来不错,但我不知道如何有效地获得中心白框的角坐标。稍后我会有其他类似的图像,其中中央灰色矩形可以有不同的大小,所以我希望优化代码以适应 future 。
我尝试了来自 OpenCV - How to find rectangle contour of a rectangle with round corner? 的其他示例和 OpenCV/Python: cv2.minAreaRect won't return a rotated rectangle .最后一个给我https://imgur.com/E4Gl8Z6最佳设置。
感谢任何帮助!谢谢。
最佳答案
如果您正在寻找 python 代码来实现更多功能,您可以在此存储库中找到它...
https://github.com/DevashishPrasad/Angle-Distance
因此,为了解决您的问题,这段代码可能会有所帮助 -
# import the necessary packages
from imutils import perspective
from imutils import contours
import numpy as np
import imutils
import cv2
# load the image, convert it to grayscale, and blur it slightly
image = cv2.imread("test.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)
# perform edge detection, then perform a dilation + erosion to
# close gaps in between object edges
edged = cv2.Canny(gray, 50, 100)
edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)
# find contours in the edge map
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
# loop over the contours individually
for c in cnts:
# This is to ignore that small hair countour which is not big enough
if cv2.contourArea(c) < 1000:
continue
# compute the rotated bounding box of the contour
box = cv2.minAreaRect(c)
box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)
box = np.array(box, dtype="int")
# order the points in the contour such that they appear
# in top-left, top-right, bottom-right, and bottom-left
# order, then draw the outline of the rotated bounding
# box
box = perspective.order_points(box)
# draw the contours on the image
orig = image.copy()
cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 5)
# loop over the original points
for (xA, yA) in list(box):
# draw circles corresponding to the current points and
cv2.circle(orig, (int(xA), int(yA)), 9, (0,0,255), -1)
cv2.putText(orig, "({},{})".format(xA, yA), (int(xA - 50), int(yA - 10) - 20),
cv2.FONT_HERSHEY_SIMPLEX, 1.8, (255,0,0), 5)
# show the output image, resize it as per your requirements
cv2.imshow("Image", cv2.resize(orig,(800,600)))
cv2.waitKey(0)
评论说明一切
关于python - OpenCV/Python - 从灰度图像中查找灰度图案矩形的角坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50957574/