RocK_st4r
RocK_st4r

Reputation: 5

Cropping out black borders in image

I need if there is way how to crop out black parts on right and left side of this image image to crop[image to crop out black parts]. I would like to use openCV, python. I have issue to crop out curved lines. Thank you for help.

https://i.sstatic.net/a8jt0.jpg

Upvotes: 0

Views: 5512

Answers (2)

fmw42
fmw42

Reputation: 53089

You cannot crop out corners of an image. But you can turn them transparent. You can convert the image to grayscale, threshold those areas to black and the rest to white and use that as a mask. Put the mask into the alpha channel and the corners will be transparent. Here is an example using Python/OpenCV.

Input:

enter image description here

import cv2
import numpy as np

# load image as grayscale
img = cv2.imread('retina.jpeg')

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

# threshold input image using otsu thresholding as mask and refine with morphology
ret, mask = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) 
kernel = np.ones((9,9), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

# put mask into alpha channel of image
result = img.copy()
result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
result[:, :, 3] = mask

# save resulting masked image
cv2.imwrite('retina_masked.png', result)

# display result, though it won't show transparency
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()


enter image description here

Upvotes: 4

O Yahya
O Yahya

Reputation: 376

Image is essentially a pixels array, so when you say crop an image, I translate it to delete elements from an array. So to delete certain elements from an array, its size will have to change, and as we all know array size cannot be changed after declaration in C++. However you can filter through the pixels you want and copy them to a new array. I don't have a working code but hopefully the below code will give you a push

for (int i = 0; i < image.rows; i++) { 

for (int j = 0; j < image.cols; j++) { 

    if (image.at<Vec3b>(i, j)[0] != 0 && image.at<Vec3b>(i, j)[1] != 0 && image.at<Vec3b>(i, j)[2] != 0) { /*Check if all the RGB pixels are not 0 (not black)*/
        /*TODO*/
        /*MOVE THIS PIXEL TO A NEW ARRAY*/
    }
}

}

Upvotes: 0

Related Questions