Home > Blockchain >  Crop an image around an object in Python
Crop an image around an object in Python

Time:01-27

I have for example Example image where the object of interest is white and the rest of the image is black. Is there any way to crop the image in python so that all that is left is a rectangle that has the white mask in it?

The end result should look something like this: Cropped image

CodePudding user response:

You can use OpenCV to achieve this.

import cv2

# Read the image
img = cv2.imread('example.jpg')

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

# Find the contours
contours, hierarchy = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Find the bounding rectangle of the largest contour
x, y, w, h = cv2.boundingRect(contours[0])

# Crop the image
cropped = img[y:y h, x:x w]

# Save the cropped image
cv2.imwrite('cropped.jpg', cropped)

CodePudding user response:

use can you pillow library it has a crop function

  • Related