首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检测二维图像中的标记[Python/OpenCV]

检测二维图像中的标记[Python/OpenCV]
EN

Stack Overflow用户
提问于 2016-05-05 04:13:47
回答 2查看 2.9K关注 0票数 6

我想在Python中创建一个脚本(使用OpenCV库)来确定图片中有哪些标记。标记看起来像这样:

Markers

加载图像后,脚本应打印图片中的标记(返回标记的数量)。例如,如果我加载此图片:

Image with markers

对于这个图像,脚本应该返回三个数字: 1,2和3。我有一个脚本,它加载图像并识别图形(圆圈,正方形等-在脚本中只有正方形),但我没有任何想法来识别整个标记,它由几个数字组成。有什么想法吗?关于算法或任何解决方案,请提供任何建议。

代码语言:javascript
复制
import numpy as np
import cv2

img = cv2.imread('B.jpg')
gray = cv2.imread('B.jpg',0)

ret,thresh = cv2.threshold(gray,120,255,1)

contours,h = cv2.findContours(thresh,1,2)

for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    print len(approx)
    if len(approx)==4:
        print "square"
        cv2.drawContours(img,[cnt],0,(0,0,255))

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

但很明显,这不是我需要的,它只是围绕着矩形。谢谢你的建议和帮助。

EN

回答 2

Stack Overflow用户

发布于 2016-05-05 16:55:14

首先,我尝试使用特征匹配(由@tfv用户提出),但这可能不是一个好的解决方案。在许多方法中,它给出了太多的匹配(但图像完全不同)或太少的匹配(当图像相同时)

现在我将尝试使用@Micka的算法,但我对第二点和第三点有一个问题。我在上面的帖子中的代码是find squares。如何将新矩形保存为新图像?

票数 0
EN

Stack Overflow用户

发布于 2021-06-07 09:48:15

特征匹配的性能将很差,因为这些标记的特征非常少(您需要用于特征匹配的角点群集和精细细节)。

这些标记更适合于Template Matching方案。对于正确的模板类型,输入图像和模板之间的相关性将是最高的(假设模板已正确定位、定向和缩放)。以下代码适用于您的示例。它包括许多必要的预处理,但本质是找到最高相关性:np.correlate(img.flatten(), templ.flatten())。代码可以在许多方面进行改进,以使其对标记位置、比例、方向、噪声等变化更加健壮。

代码语言:javascript
复制
import matplotlib.pyplot as plt
import numpy as np
import cv2

# Detect and store the 6 templates (markers)
fig0, axs0 = plt.subplots(2)
imgs = cv2.imread("markers.png")
imgs_gray = cv2.cvtColor(imgs, cv2.COLOR_BGR2GRAY)
ret, imgs_th = cv2.threshold(imgs_gray, 100, 255, cv2.THRESH_BINARY)
xywh = np.zeros((0, 4), dtype=np.int32)
contours, hierarchies = cv2.findContours(
    imgs_th, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
)
for idx, c in enumerate(contours):
    if hierarchies[0, idx, 3] == 0 and cv2.contourArea(c) > 20000:
        x, y, w, h = cv2.boundingRect(c)
        xywh = np.vstack((xywh, np.array([x, y, w, h])))
axs0[0].set_title("thresholded markers image")
axs0[0].imshow(imgs_th, cmap="gray")
sortx_xywh = xywh[np.argsort(xywh[:, 0])]
sortyx_xywh = sortx_xywh[np.argsort(sortx_xywh[:, 1])]
max_w = np.amax(sortyx_xywh[:, 2])
max_h = np.amax(sortyx_xywh[:, 3])
templates = np.zeros((max_h, max_w, 6))
for i, xy in enumerate(sortyx_xywh[:, 0:2]):
    templates[:, :, i] = imgs_th[xy[1] : xy[1] + max_h, xy[0] : xy[0] + max_w]

# Detect the marker regions in the input image
img_in = cv2.imread("input.jpg")
img_gray = cv2.cvtColor(img_in, cv2.COLOR_BGR2GRAY)
ret, img_th = cv2.threshold(img_gray, 100, 255, cv2.THRESH_BINARY)
xywh = np.zeros((0, 4), dtype=np.int32)
contours, hierarchies = cv2.findContours(img_th, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for idx, c in enumerate(contours):
    if hierarchies[0, idx, 3] == 0 and cv2.contourArea(c) > 20000:
        x, y, w, h = cv2.boundingRect(c)
        xywh = np.vstack((xywh, np.array([x, y, w, h])))
axs0[1].set_title("thresholded input  image")
axs0[1].imshow(img_th, cmap="gray")
fig0.show()

# Use simplified template matching (correlation) to determine marker type and orientation
for xy in xywh[:, 0:2]:
    fig1, axs1 = plt.subplots(5, 6)
    img = img_th[xy[1] : xy[1] + max_h, xy[0] : xy[0] + max_w]
    axs1[0, 0].imshow(img, cmap="gray")
    axs1[0, 0].set_title("input image")
    corr = np.zeros((4, 6))
    for t in range(6):  # 6 templates
        templ = templates[:, :, t]
        for o in range(4):  # 4 orientations
            corr[o, t] = np.correlate(img.flatten(), templ.flatten())
            axs1[o + 1, t].imshow(templ, cmap="gray")
            axs1[o + 1, t].set_title("corr = {:.2e}".format(corr[o, t]))
            templ = np.rot90(templ)
    rot, typ = np.unravel_index(np.argmax(corr, axis=None), corr.shape)
    print("Input marker at ({},{}) is type {}, rotated {} degrees.".format(xy[0], xy[1], typ + 1, rot * 90))
    fig1.tight_layout(pad=0.001)
    fig1.show()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37037187

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档