【发布时间】:2021-09-16 01:00:02
【问题描述】:
我有一些示例图片如下
到目前为止,我有代码可以使用模板并删除边框以获得第一个结果
import cv2
import numpy as np
def remove_templates(image):
templates = ['images/sample1.jpeg', 'images/sample2.jpeg']
for template in templates:
template = cv2.imread(template)
h, w, _ = template.shape
res = cv2.matchTemplate(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), cv2.cvtColor(template, cv2.COLOR_BGR2GRAY), cv2.TM_CCOEFF)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(img, top_left, bottom_right, (1, 1, 1), -1)
def crop_borders(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = 255 * (gray < 128).astype(np.uint8) # To invert the text to white
gray = cv2.morphologyEx(gray, cv2.MORPH_OPEN, np.ones((2, 2), dtype=np.uint8)) # Perform noise filtering
canny = cv2.Canny(gray, 0, 150)
coords = cv2.findNonZero(canny) # Find all non-zero points (text)
x, y, w, h = cv2.boundingRect(coords) # Find minimum spanning bounding box
rect = img[y:y + h, x:x + w + 20] # Crop the image - note we do this on the original image
return rect
img = cv2.imread('images/res5.jpg')
remove_templates(img)
img = crop_borders(img)
cv2.imwrite('output/op1.png', img)
cv2.imwrite('output/op2.png', cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
height = img.shape[0]
width = img.shape[1]
# Cut the image in half
width_cutoff = (width // 2)
left = img[:, :width_cutoff+5]
right = img[:, width_cutoff+25:]
cv2.imwrite('output/left.png', left)
cv2.imwrite('output/right.png', right)
上面的代码确实给了我第一个结果,但是当徽标的纵横比或大小不同时失败。
我怎样才能做到这一点,任何帮助都会非常有帮助。
我是opencv的新手,所以任何方向都会有所帮助。我现在拥有的大部分代码都是从不同的教程中挑选的。如果代码有问题,请指导我。
【问题讨论】:
-
为此,您有什么想法或在网上找到的?
-
您需要在图像上绘制矩形。我正在分享相同的参考。我希望你能实现它。 docs.opencv.org/3.4/da/d0c/tutorial_bounding_rects_circles.html
-
@ChristophRackwitz 在代码中,我试图找到模板并用黑色反应角替换它们,然后裁剪图像以删除边框。但是,如果纵横比或大小不同,则模板不匹配。之后我打算画线可能使用精明和轮廓检测
-
那么,哪个图像是起点?第二个还是第三个?
-
还有,ROI 的数量……这是一个常数吗……如果不是,它是否以起始图像而闻名?