Home > Enterprise >  opencv-python: how to crop image with bounding box coordinates
opencv-python: how to crop image with bounding box coordinates

Time:11-28

I recognized pink wood in an image which is identified in the image below with the green box. Now I want to crop the image based on the box coordinates. I describe what I mean with a picture.

bounding box coordinate: x, y, w, h = (50, 1034, 119, 72)

input image

output expected (Manually cropped)

image1 - crop coordinates from the beginning of the image to the beginning of pink wood(bounding box)

image2 - crop coordinates from the end of the pink wood(bounding box)to the end of the image

for image 1 I wrote the blow code but it is wrong.

x, y => beginning of the image (0,0)

x, y => beginning of pink wood (50 1034)

from PIL import Image
img = Image.open("img.png")
img2 = img.crop((0, 0, 50, 1034))
img2.save("1.png")

CodePudding user response:

You can select your area of interest as an array:

import cv2

imagepath = yourPath
im = cv2.imread(imagepath)

imh, imw, _ = im.shape
x, y, w, h = (50, 1034, 119, 72)

img1 = im[:y, :]
img2 = im[y h:imh, :]

cv2.imwrite('img1.tif', img1)
cv2.imwrite('img2.tif', img2)

  • Related