简体   繁体   English

给定要裁剪的四个角的坐标,如何裁剪图像

[英]How do I crop an image given the coordinates of the four corners to crop

I need to crop the license plate out of a car's image with python given the coordinates for bounding boxes of the plate. 给定车牌边界框的坐标,我需要使用python从汽车图像中裁剪车牌。 (4 coordinates) . (4个坐标)。 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. 谢谢。

In OpenCV you can do the following if you want to crop the plate 在OpenCV中,如果要裁剪板,可以执行以下操作

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 在此也回答: 如何使用Python在OpenCV中裁剪图像

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]

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 x1,y1:1112 711
x2, y2: 1328 698 x2,y2:1328698
x3, y3: 1330 749 x3,y3:1330 749
x4, y4: 1115 761 x4,y4:1115761

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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