简体   繁体   中英

Crop bounding boxes using python

Code to get coordinates of bounding boxes:

width=600
height=900
for box,score,cls in zip(detections['detection_boxes']  [0],detections['detection_scores'][0],detections['detection_classes'][0]):
   if score >= 0.5: # or any other value
      xmin = box[1]*width
      ymin = box[0]*height
      xmax = box[3]*width
      ymax = box[2]*height
      print("xmin: {} ".format(xmin),"ymin: {}".format(ymin),"xmax: {}".format(xmax),"ymax: {}".format(ymax))

It gives: 在此处输入图像描述

Now I want to crop image given these bounding boxes. How I can crop all these coordinates and store as jpg file?

If you want to use tensorflow you can use:

cropped_image_tensor = tf.image.crop_to_bounding_box(image, xmin, ymin, height, width)

and then from tensor to image with:

output_image = tf.image.encode_png(cropped_image_tensor)

If you have stored your image as a numpy array you could use this on your image:

cropped_image = image[ymin:ymax, xmin:xmax:, :]

where I assumed your image dimension is height, width, number of channels.

Then save the image as jpg with:

from PIL import Image

im = Image.fromarray(cropped_image)
im.save("your_file.jpeg")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM