Alex Rivera | Logout

How to remove black part from the image?

Asked 2012-05-17T09:00:18.173
13

I have stitched two images together using OpenCV functions and C++. Now I am facing a problem that the final image contains a large black part.

The final image should be a rectangle containing the effective part. My image is the following:

enter image description here

How can I remove the black section?

Edit
Report

1 Answer

24

mevatron's answer is one way where amount of black region is minimised while retaining full image.

Another option is removing complete black region where you also loose some part of image, but result will be a neat looking rectangular image. Below is the Python code.

Here, you find three main corners of the image as below:

enter image description here

I have marked those values. (1,x2), (x1,1), (x3,y3). It is based on the assumption that your image starts from (1,1).

Code :

First steps are same as mevatron's. Blur the image to remove noise, threshold the image, then find contours.

import cv2
import numpy as np

img = cv2.imread('office.jpg')
img = cv2.resize(img,(800,400))

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = cv2.medianBlur(gray,3)

ret,thresh = cv2.threshold(gray,1,255,0)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

Now find the biggest contour which is your image. It is to avoid noise in case if any (Most probably there won't be any). Or you can use mevatron's method.

max_area = -1
best_cnt = None

for cnt in contours:
    
    area = cv2.contourArea(cnt)
    if area > max_area:
        max_area = area
        best_cnt = cnt

Now approximate the contour to remove unnecessary points in contour values found, but it preserve all corner values.

approx = cv2.approxPolyDP(best_cnt,0.01*cv2.arcLength(best_cnt,True),True)

Now we find the corners.

First, we find (x3,y3). It is farthest point. So x3*y3 will be very large. So we find products of all pair of points and select the pair with maximum product.

far = approx[np.product(approx,2).argmax()][0]

Next (1,x2). It is the point where first element is one,then

answered 2012-05-18T05:29:27.537

Your Answer