how to cut a contour from an image and save it to a new file

computer-vision, opencv, python

Solution

I do some work on this, and crop the region as follow. I think it is what you want.

Basicly speaking, I do those operations on the image.

1. medianBlur the image, threshold and do morph-op.

2. project to the axis, threshold and get the bound.

3. crop the region.

#!/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)

Problem

Hello everyone this is my first question so please be gentle. I have a project in computer vision field in which I'm new and i would appreciate some help. I have an image of a pcb and my (first of all) task is to cut off the board from the background and save it to a new file. It wouldn't be a problem if the result was just the plain pcb without the grey background. What i have tried so far is, firstly convert the image to binary using threshold. Then i searched for contours using cv2.findContours and after finding them i sorted the contours and drew the biggest after some research i found a way to cut the contour and save it to a new image. I used x,y,w,h = cv2.boundingRect to find the width and height of the contour and [y:y+h,x:x+w] to save only the contour. The problem is that, with this method i take some background too for some reason as you can see in pic3. Is there any way to cut off the board so the result would be the black rectangle in image pic1 or at least the board without the grey background? UPDATE I managed to make the mask and do bitwise_and but the result is the board with black background.the result can someone help me to remove the black background and leave only the board in image? Thank you!

Original source