如何使用opencv识别和标记形状

2024-04-24 05:38:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用opencv创建一个围绕圆锥体的矩形。我目前所处的位置是,我已经概述了生成三角形形状的代码。如何使用opencv围绕三角形创建矩形

到目前为止,我的代码是:

import cv2
import numpy as np

img = cv2.imread('image.jpg')

ret, mask = cv2.threshold(img[:, :,2], 235, 255, cv2.THRESH_BINARY)

mask3 = np.zeros_like(img)
mask3[:, :, 0] = mask
mask3[:, :, 1] = mask
mask3[:, :, 2] = mask

orange = cv2.bitwise_and(img, mask3)


cv2.imwrite("output.jpg", orange)

im = cv2.imread('output.jpg')

imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(im, contours, -1, (0,255,0), 3)
cv2.imshow('img',im)

cv2.waitKey(0)
cv2.destroyAllWindows

Jpeg文件: enter image description here


Tags: 代码importimgthresholdnpmaskcv2opencv
1条回答
网友
1楼 · 发布于 2024-04-24 05:38:50

一种方法是使用多尺度模板匹配

    1. 裁剪要查找的对象:

      enter image description here

    1. 应用Canny边缘检测来发现边缘
    edged = cv2.Canny(resized, 50, 200)
    
    1. 使用matchTemplate查找匹配的模板
    result = cv2.matchTemplate(edged, template, cv2.TM_CCOEFF)
    

结果:

enter image description here

代码:

import numpy as np
import imutils
import glob
import cv2

template = cv2.imread("template.jpg")
template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
template = cv2.Canny(template, 50, 200)
(h, w) = template.shape[:2]

for imagePath in glob.glob("img2" + "/pXobJ.jpg"):
    image = cv2.imread(imagePath)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    found = None

    for scale in np.linspace(0.2, 1.0, 20)[::-1]:
        resized = imutils.resize(gray, width=int(gray.shape[1] * scale))
        r = gray.shape[1] / float(resized.shape[1])

        if resized.shape[0] < h or resized.shape[1] < w:
            break

        edged = cv2.Canny(resized, 50, 200)
        result = cv2.matchTemplate(edged, template, cv2.TM_CCOEFF)
        (_, maxVal, _, maxLoc) = cv2.minMaxLoc(result)

        if found is None or maxVal > found[0]:
            found = (maxVal, maxLoc, r)

    (_, maxLoc, r) = found
    (startX, startY) = (int(maxLoc[0] * r), int(maxLoc[1] * r))
    (endX, endY) = (int((maxLoc[0] + w) * r), int((maxLoc[1] + h) * r))

    cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2)
    cv2.imwrite("img2/out.jpg", image)
    print("Table coordinates: ({}, {}, {}, {})".format(startX, startY, endX, endY))
  • 您还可以通过经过训练的网络使用深度学习对象检测

相关问题 更多 >