How to cut a path from an image and save it in a new file

Hi everyone, this is my first question, so please be careful. I have a project in the field of computer vision in which I am a beginner, and I would appreciate help. I have a pcb image, and my (first of all) task is to disconnect the panel from the background and save it in a new file.

the desired image of the result is within the black rectangle-pic1

There would be no problem if the result was just plain pcb without a gray background.

What I have tried so far is to first convert the image to binary using a threshold . Then I searched for paths using cv2.findContours , and after searching for them, I sorted the paths and drew the largest

. x, y, w, h = cv2.boundingRect, [y: y + h, x: x + w] . , , pic3.

, pic1 , , ?

UPDATE bitwise_and, . ? !

+4
1

. , , .

enter image description here

enter image description here


, .

1. , do 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)
+2

Source: https://habr.com/ru/post/1659229/


All Articles