'How to crop image based on the object radius using OpenCV?

I'm new to python. I know basics about image-preprocessing. I don't know how to remove background and crop an image using OpenCV.

image1



Solution 1:[1]

Here is the processing in Python/OpenCV for your new image.

Input:

enter image description here

import cv2
import numpy as np

# load image as grayscale
img = cv2.imread('Diabetic-Retinopathy_G_RM_151064169.jpg')

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

# threshold input image
mask = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)[1]

# optional morphology to clean up small spots
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

# put mask into alpha channel of image
result = np.dstack((img, mask))

# save resulting masked image
cv2.imwrite('Diabetic-Retinopathy_G_RM_151064169_masked.png', result)

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

Result

Solution 2:[2]

Here is one way to do that in Python/OpenCV.

  • Read input
  • Convert to grayscale
  • Threshold and invert as mask
  • Put mask into alpha channel of input
  • Save result

Input:

enter image description here

import cv2
import numpy as np

# load image
img = cv2.imread('black_circle.png')

# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold
threshold = cv2.threshold(gray,128,255,cv2.THRESH_BINARY)[1]

# invert so circle is white on black
mask = 255 - threshold

# put mask into alpha channel of image
result = np.dstack((img, mask))

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

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

Result:

enter image description here

Note: download the result to see the transparency.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fmw42
Solution 2 fmw42