【问题标题】:Copy shape to blank canvas (OpenCV, Python)将形状复制到空白画布(OpenCV、Python)
【发布时间】:2018-01-13 21:09:35
【问题描述】:
import numpy as np
import cv2

blank_image = np.zeros((40,40,3), np.uint8)
blank_image.fill(255)

#cv2.imshow('i', blank_image)
#cv2.waitKey(0)

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

cnt = contours[4]
cnts = cv2.drawContours(im,[cnt],0,(255,0,0), -1)

cv2.imshow('i', im)
cv2.waitKey(0)

for a in cnt:
    print(a) #this contour is a 3D numpy array

源图片:

我正在使用此代码: 1. 创建一个 40x40 像素的白色画布 2. 使用Opencv函数findContours找到数字(本例中为5)的轮廓。

我想要做的是将这个形状(请,不是边界框或矩形,蓝色形状)复制到画布中。

经过一些研究,我了解到 opencv 图像只是一个 numpy 数组。理论上,这个数组应该在新图像(我的白色画布..)中翻译,然后使用数组中的值重建形状。我说的对吗?

有人知道怎么做吗?在某些情况下,围绕数字创建边界框/矩形会导致不准确。请不要把它作为解决方案。我已经用至少 3-4 种不同的方式完成了这个过程,结果还不够令人满意。

因此,所需的输出将是这样的......

谢谢。

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    对于轮廓图像

    我想像这样的东西


    对于125等打开的号码,很容易做到:从整个图像中裁剪,或在新图像上绘制。对于0689等封闭号码,需要更多的步骤。这是5 的示例,您将获得


    详情和说明在代码中。

    #!/usr/bin/python3
    # 2018.01.14 09:48:15 CST
    # 2018.01.14 11:39:03 CST
    
    import numpy as np
    import cv2
    
    im = cv2.imread('test.png')
    imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(imgray, 127, 255, 0)
    contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]
    
    
    ## this contour is a 3D numpy array
    cnt = contours[4]
    res = cv2.drawContours(im,[cnt],0,(255,0,0), -1)
    cv2.imwrite("contours.png", res)
    
    ## Method 1: crop the region
    x,y,w,h = cv2.boundingRect(cnt)
    croped = res[y:y+h, x:x+w]
    cv2.imwrite("croped.png", croped)
    
    ## Method 2: draw on blank
    # get the 0-indexed coords
    offset = cnt.min(axis=0)
    cnt = cnt - cnt.min(axis=0)
    max_xy = cnt.max(axis=0) + 1
    w,h = max_xy[0][0], max_xy[0][1]
    # draw on blank
    canvas = np.ones((h,w,3), np.uint8)*255
    cv2.drawContours(canvas, [cnt], -1, (255,0,0), -1)
    cv2.imwrite("canvas.png", canvas)
    

    【讨论】:

    • 是的!最后!您是否确认使用第二种方法仅裁剪轮廓,然后将其粘贴到画布中?这是完美的。谢谢。
    • 另外,有没有办法定义轮廓的 minArea 来检测?例如,数字 8 填充了我在 drawContours 中选择的颜色:example...
    猜你喜欢
    • 2021-09-19
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    相关资源
    最近更新 更多