我有一个1920x1080的图片。我需要获取图像中每个矩形的位置。最好是2点(左上,右下)。
我对Python相当陌生。我想也许使用opencv模块,但是如果您能给我一些指导,那将非常有帮助。
谢谢。
答案 0 :(得分:2)
我建议像这样使用 OpenCV findContours()
:
#!/usr/bin/env python3
import numpy as np
import cv2
# Load image
im = cv2.imread('pattern.png')
# Convert to grayscale
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
# Find contours, draw on image and save
im2, contours, hierarchy = cv2.findContours(imgray,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(im, contours, -1, (0,0,255), 3)
# Show user what we found
i=0
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
print('Contour {}: x={}, y={}, w={}, h={}'.format(i,x,y,w,h))
i = i+1
# Save the result
cv2.imwrite('result.png',im)
示例输出
Contour 0: x=1743, y=903, w=77, h=77
Contour 1: x=1552, y=903, w=77, h=77
Contour 2: x=291, y=903, w=77, h=77
Contour 3: x=100, y=903, w=77, h=77
Contour 4: x=1648, y=808, w=77, h=77
Contour 5: x=196, y=808, w=77, h=77
Contour 6: x=1743, y=712, w=77, h=77
Contour 7: x=291, y=712, w=77, h=77
Contour 8: x=100, y=712, w=77, h=77
Contour 9: x=1551, y=711, w=78, h=78
Contour 10: x=1017, y=597, w=77, h=77
Contour 11: x=826, y=597, w=77, h=77
Contour 12: x=922, y=502, w=77, h=77
Contour 13: x=1017, y=406, w=77, h=77
Contour 14: x=826, y=406, w=77, h=77
Contour 15: x=1743, y=291, w=77, h=77
Contour 16: x=1552, y=291, w=77, h=77
Contour 17: x=291, y=291, w=77, h=77
Contour 18: x=100, y=291, w=77, h=77
Contour 19: x=1648, y=196, w=77, h=77
Contour 20: x=196, y=196, w=77, h=77
Contour 21: x=1743, y=100, w=77, h=77
Contour 22: x=1552, y=100, w=77, h=77
Contour 23: x=291, y=100, w=77, h=77
Contour 24: x=100, y=100, w=77, h=77
请注意,这并不是在专门寻找图案,而是在黑色背景上寻找白色物体。这具有优点和缺点。优点是它可以在不更改代码的情况下适用于任何白色形状(圆形,星形,八边形)。它也可能比模板匹配更快。缺点是,如果图像中还有其他白色物体,尽管您可以检查形状,圆形度,颜色或其他可以确认/消除歧义的物体,但它会给您带来误报。
答案 1 :(得分:1)
您要寻找的关键字是模板匹配。它基本上是在整个图像中搜索“模板”的副本。换句话说,正是您要找的东西!
一些示例代码可以在这里找到: https://docs.opencv.org/3.3.0/d4/dc6/tutorial_py_template_matching.html
import cv2
import numpy as np
from matplotlib import pyplot as plt
img_rgb = cv2.imread('mario.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('mario_coin.png',0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
cv2.imwrite('res.png',img_rgb)
其中mario_coin.png是您的矩形,而mario.png是您的全尺寸图片。