OpenCV Python裁剪图像 [英] OpenCV python cropping image
问题描述
我创建了黑色图像,而不是在该图像中绘制了一个红色矩形.之后,我裁剪了该图像,并使用命令在裁剪图像中绘制了另一个矩形. cv2.rectangle(crop,(50,50),(150,150),(0,0,255),3)
I've created black image, than I drew a red rectangle into this image. Afterwards I cropped this image and drew a another rectangle into the cropped image using the command. cv2.rectangle(crop,(50,50),(150,150),(0,0,255),3)
为什么在最后显示第二个矩形时它会出现在原始图像中?我希望只看到第一个矩形.
Why does this second rectangle appears in the original image when I show it at the end? I expected to see just the first rectangle.
import cv2
import numpy as np
#create image
image = np.zeros((400,400,3), np.uint8)
#draw rectangle into original image
cv2.rectangle(image,(100,100),(300,300),(0,0,255),3)
#crop image
crop = image[100:300,100:300]
#draw rectangle into cropped image
cv2.rectangle(crop,(50,50),(150,150),(0,0,255),3)
cv2.imshow('Result', image)
cv2.waitKey()
cv2.destroyAllWindows()
推荐答案
crop = image[100:300,100:300]
在原始图像上创建一个 view ,而不是一个新对象.修改该视图将修改基础原始图像.请参见 http://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html有关更多详细信息.
crop = image[100:300,100:300]
creates a view on the original image instead of a new object. Modifying that view will modify the underlying original image. See http://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html for more details.
您可以通过在裁剪时创建一个副本来解决此问题:
crop = image[100:300,100:300].copy()
.
You can resolve this issue by creating a copy when cropping:
crop = image[100:300,100:300].copy()
.
注意:image[100:300,100:300]
参数是y: y+h, x: x+w
而不是x: x+w, y: y+h
这篇关于OpenCV Python裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!