首页 文章

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

提问于
浏览
4

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

the desired result image is within the black rectangle-pic1

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

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

经过一些研究,我发现了一种切割轮廓并将其保存为新图像的方法 . 我用 x,y,w,h = cv2.boundingRect 找到轮廓的宽度和高度, [y:y+h,x:x+w] 只保存轮廓 . 问题是,使用这种方法我也会因为某些原因而考虑一些背景,如pic3所示 .

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

UPDATE 我设法制作了面具并做了bitwise_and但结果却是黑色背景的黑板 . the result有人可以帮我删除黑色背景并仅留下图像中的纸板吗?谢谢!

1 回答

  • 2

    我做了一些工作,并按照以下方式裁剪区域 . 我想这就是你想要的 .

    enter image description here

    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)
    

相关问题