如何从图像中剪切轮廓并将其保存到新文件

时间:2016-10-28 20:46:47

标签: python opencv computer-vision

大家好,这是我的第一个问题所以请保持温和。我有一个计算机视觉领域的项目,我是新的,我会很感激一些帮助。我有一个pcb的图像,我的(首先)任务是从背景中切断电路板并将其保存到新文件。

the desired result image is within the black rectangle-pic1

如果结果只是没有灰色背景的普通pcb,那就没问题了。

我到目前为止尝试的是,首先使用阈值将图像转换为二进制。然后我使用 cv2.findContours 搜索轮廓,找到它们后我对轮廓进行了排序并绘制了最大的

经过一些研究,我发现了一种切割轮廓并将其保存到新图像的方法。我使用 x,y,w,h = cv2.boundingRect 来查找轮廓的宽度和高度, [y:y + h,x:x + w] 仅保存轮廓。问题在于,使用这种方法我也会因为某种原因而考虑一些背景,你可以在pic3中看到。

有没有办法切断电路板,结果是图像pic1中的黑色矩形或至少没有灰色背景的电路板?

更新 我设法制作了面具并做了bitwise_and,但结果是黑色背景的电路板。the result有人可以帮我删除黑色背景并只留下图像中的电路板吗? 谢谢!

1 个答案:

答案 0 :(得分:2)

我在这方面做了一些工作,并按如下方式裁剪区域。我认为这就是你想要的。

https://github.com/angular/angularfire2/issues/1199

enter image description here

基本上,我会对图像进行操作。

1。 medianBlur图像,阈值和变形操作。

2。投射到轴,阈值并获得约束。

3. 裁剪区域。

#!/usr/bin/python3
# 2017.10.04 23:45:01 CST
# 2017.10.05 00:52:26 CST

#how to cut a contour from an image and save it to a new file

from matplotlib import pyplot as plt
import numpy as np
import cv2
import time

imgname = "pcb.jpg"
img = cv2.imread(imgname)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

## medianBlur, threshold and morph-close-op
median = cv2.medianBlur(gray, ksize=17)
retval, threshed = cv2.threshold(median, 110, 255, cv2.THRESH_BINARY_INV)
closed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, np.ones(15,15))

## Project to the axis
H,W = img.shape[:2]
xx = np.sum(closed, axis=0)/H
yy = np.sum(closed, axis=1)/W

## Threshold and find the nozero
xx[xx<60] = 0
yy[yy<100] = 0

ixx = xx.nonzero()
iyy = yy.nonzero()
x1,x2 = ixx[0][0], ixx[0][-1]
y1,y2 = iyy[0][0], iyy[0][-1]

## label on the original image and save it.
res1 = cv2.rectangle(img.copy(), (x1,y1),(x2,y2), (0,0,255),2)
res2 = img[y1:y2,x1:x2]
cv2.imwrite("result1.png", res1)
cv2.imwrite("result2.png", res2)