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

2024-05-29 07:33:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

the desired result image is within the black rectangle-pic1

如果结果只是没有灰色背景的普通pcb就不会有问题。在

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

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

有没有什么方法可以切断电路板,使其结果是图像pic1中的黑色矩形,或者至少是没有灰色背景的电路板?在

the result有人能帮我去掉黑色背景,只留下板在图像中吗? 谢谢您!在


Tags: 文件项目方法图像计算机阈值视觉cv2
0条回答
网友
1楼 · 发布于 2024-05-29 07:33:55

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

enter image description here

enter image description here


基本上,我对图像做这些操作。在

1。median模糊图像、阈值并执行morph-op

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)

相关问题 更多 >

    热门问题