Eug*_*ush 6 python opencv computer-vision
大家好,这是我的第一个问题,请保持温柔。我有一个计算机视觉领域的项目,我是新手,我将不胜感激。我有一个PCB的图像,我的任务(首先)是从后台切断电路板,并将其保存到新文件中。
如果结果只是没有灰色背景的纯pcb,那将不是问题。
到目前为止,我尝试过的是,首先使用threshold将图像转换为二进制。然后,我使用cv2.findContours搜索轮廓,找到它们之后,我对轮廓进行了排序并画出了最大的轮廓
经过一番研究,我找到了一种切割轮廓并将其保存为新图像的方法。我使用x,y,w,h = cv2.boundingRect来查找轮廓的宽度和高度,并使用[y:y + h,x:x + w]仅保存轮廓。问题是,由于这种原因,我也需要一些背景知识,如您在pic3中所见。
有什么方法可以切断电路板,以便结果是图像pic1中的黑色矩形,或者至少是没有灰色背景的电路板?
更新 我设法制作了面具,并做了bitwise_and,但结果是黑色背景的电路板。结果是有人可以帮助我删除黑色背景,而仅将木板留在图像中吗?谢谢!
我对此做了一些工作,并按如下方式裁剪该区域。我想这就是你想要的。
基本上来说,我对图像进行这些操作。
1.中值模糊图像,阈值并进行变形操作。
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)
Run Code Online (Sandbox Code Playgroud)