大家好,這是我的第一個問題所以請保持溫和.我有一個計算機視覺領域的項目,我是新的,我會很感激一些幫助.我有一個pcb的圖像,我的(首先)任務是從背景中切斷電路板并將其保存到新文件.
如果結果只是沒有灰色背景的普通pcb,那就沒問題了.
我到目前為止嘗試的是,首先使用閾值將圖像轉換為二進制.然后我使用cv2.findContours搜索輪廓,找到它們后,我對輪廓進行了排序并繪制了最大的輪廓
經過一些研究,我發現了一種切割輪廓并將其保存為新圖像的方法.我使用x,y,w,h = cv2.boundingRect來查找輪廓的寬度和高度,并使用[y:y h,x:x w]來僅保存輪廓.問題是,使用這種方法我也會因為某些原因而考慮一些背景,如pic3所示.
有沒有辦法切斷電路板,所以結果將是圖像pic1中的黑色矩形或至少沒有灰色背景的電路板?
UPDATE
我設法制作了面具并做了bitwise_and,但結果是黑色background.the result板可以有人幫我刪除黑色背景并只留下圖像中的板嗎?
謝謝!
最佳答案 我做了一些工作,并按照以下方式裁剪區域.我想這就是你想要的.
基本上,我在圖像上做這些操作.
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)