Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop Image from all sides after edge detection

I am new to OpenCV. I want to extract the main object from an image. So, I have applied Canny on the image to get the edges around the main object and got the following output : enter image description here

Here is the code to get this using OpenCV in Python:

img = cv2.imread(file)
cv2.imshow("orig", img)
cv2.waitKey(0)
img = cv2.blur(img,(2,2))
gray_seg = cv2.Canny(img, 0, 50)

Now, I want to have the below image as the final output after getting only the main object in the image : enter image description here

I want to do it in an optimized manner because I have to process more that 2.5 million images. Can anyone help me with this?

like image 266
meemee Avatar asked Nov 30 '15 12:11

meemee


2 Answers

As you have found clean canny edge, then to crop the rectangle region, you should calculate the rectangle boundary.

The steps:

enter image description here

The result:

enter image description here


To calculate the canny region boundary, you can just find no-zero points, then get the min-max coords. Easy to realize using NumPy. Then crop using slice-op.

#!/usr/bin/python3
# 2018.01.20 15:18:36 CST

#!/usr/bin/python3
# 2018.01.20 15:18:36 CST

import cv2
import numpy as np
#img = cv2.imread("test.png")
img = cv2.imread("img02.png")
blurred = cv2.blur(img, (3,3))
canny = cv2.Canny(blurred, 50, 200)

## find the non-zero min-max coords of canny
pts = np.argwhere(canny>0)
y1,x1 = pts.min(axis=0)
y2,x2 = pts.max(axis=0)

## crop the region
cropped = img[y1:y2, x1:x2]
cv2.imwrite("cropped.png", cropped)

tagged = cv2.rectangle(img.copy(), (x1,y1), (x2,y2), (0,255,0), 3, cv2.LINE_AA)
cv2.imshow("tagged", tagged)
cv2.waitKey()

Of course, do boundingRect on the points works too.

like image 96
Kinght 金 Avatar answered Oct 15 '22 02:10

Kinght 金


The rect function should provide the functionality you need. An example of how to use it can be seen below.

cv::Mat image(img);
cv::Rect myROI(posX, posY, sizeX, sizeY);   
cv::Mat croppedImage = image(myROI);

This is writing in c++ but should be able to find a python equivalent.

The link below my provide more info How to crop a CvMat in OpenCV?

like image 31
Eni Avatar answered Oct 15 '22 04:10

Eni