python - 将形状复制到空白 Canvas (OpenCV,Python)

标签 python opencv

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

源图像:

src

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

out1

我想要做的是将此形状(请不要将边界框或矩形,而不是蓝色形状)复制到 Canvas 中。

经过一些研究,我了解到opencv镜像只是一个numpy数组。从理论上讲,应将此数组转换为新图像(白色 Canvas ),然后使用数组中的值重建形状。我是对的 ?

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

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

out2

谢谢。

最佳答案

对于轮廓图像enter image description here

我想想要像enter image description here

对于打开的数字,例如125,很容易做到:从整个图像中裁剪,或使用新图像。对于诸如0689的封闭数字,需要更多步骤。这是5的示例,您将获得enter image description here

详细信息和描述在代码中。

#!/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)

关于python - 将形状复制到空白 Canvas (OpenCV,Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48244328/

相关文章:

python - 在安装了 Anaconda 的 Windows 上获取 CUDA 和 CUDNN 版本

c++ - 纹理绑定(bind) : OpenGL + OpenCV

Python 2.7 和 OpenCV 使用 64 位和 32 位的不同结果,可能的错误?

python - 在带有 Python 或 IPython 的 Emacs 'python-mode' 中使用多个 Python shell

python - Scrapy 停止抓取但继续爬取

c++ - 为什么我在 Visual Studio 和 Qt 上编译相同的代码,却得到不同的结果?

c - 在 C 中,给定一个包含数字的图像,如何将每个单独的数字提取到单独的图像中?

iphone - cv::mat 到 UIImage 的转换无法恢复精确图像

python - 如何在具有不同日期格式的列上将字符串转换为日期

python - 如何使用 Python 编码和解码字符串以用于 URL?