5

I need to crop the license plate out of a car's image with python given the coordinates for bounding boxes of the plate. (4 coordinates) . Any tips on how I could do this ?

I have the following code , but does not work as expected.

> x1, y1: 1112 711 
> x2, y2: 1328 698 
> x3, y3: 1330 749 
> x4, y4: 1115 761
image = cv2.imread(IMAGE_PATH)
fixed_image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)

new_img = cv2.rectangle(fixed_image, (x3,y3), (x1,y1), (0, 255, 0), 5) 

plt.figure(figsize=(12,13))
plt.imshow(new_img)

Image for reference

Cropped image

Thank you.

goutham r
  • 63
  • 1
  • 1
  • 7
  • 1
    i see you tagged `opencv` so im going to assume you loaded your image with it. you can just do slicing: `image[y1:y2, x1:x2]` – Nullman Feb 26 '19 at 11:23
  • 1
    Thank you for the reply. I tried out the suggestion. I've attached the cropped image in the post. The slicing works, but some parts of the plate are left out since it's not a perfect rectangle. Any way I can avoid this ( maybe using all 4 coordinates ) ? Thanks ! – goutham r Feb 26 '19 at 12:17
  • You can also check this out https://stackoverflow.com/questions/61178736/crop-image-from-four-corner-points-using-opencv-and-python, is the same thing, just a different approach for the result. – Muneeb Ahmad Khurram May 22 '21 at 11:36

2 Answers2

6

since the coords you are getting are a POLYGON and not a RECTANGLE, you will have to make some adjustments in your slicing, the simplest to do is adjust your rectangle:

x1, y1: 1112 711
x2, y2: 1328 698
x3, y3: 1330 749
x4, y4: 1115 761

top_left_x = min([x1,x2,x3,x4])
top_left_y = min([y1,y2,y3,y4])
bot_right_x = max([x1,x2,x3,x4])
bot_right_y = max([y1,y2,y3,y4])

now you can do

img[top_left_y:bot_right_y, top_left_x:bot_right_x]

please note that slicing does NOT include the end point, so you might want to do

img[top_left_y:bot_right_y+1, top_left_x:bot_right_x+1]
Nullman
  • 4,179
  • 2
  • 14
  • 30
1

In OpenCV you can do the following if you want to crop the plate

import cv2
img = cv2.imread("image.png")
cropped__img = img[y1:y2, x1:x2]

Also answered here: How to crop an image in OpenCV using Python

Or change the colour of the pixels to white or black (or any other colour).

import cv2
img = cv2.imread("image.png")
img[y1:y2, x1:x2] = [255,255,255]
J.Maclean
  • 34
  • 1
  • 2
  • 1
    Thank you for the reply. I tried out the suggestion. I've attached the cropped image in the post. The slicing works, but some parts of the plate are left out since it's not a perfect rectangle. Any way I can avoid this ( maybe using all 4 coordinates ) ? Thanks ! – goutham r Feb 26 '19 at 12:17