[英]OpenCV python cropping image
我创建了黑色图像,然后在该图像中绘制了一个红色矩形。 之后,我裁剪了该图像,并使用命令在裁剪后的图像中绘制了另一个矩形。 cv2.rectangle(crop,(50,50),(150,150),(0,0,255),3)
为什么最后显示第二个矩形时,它会出现在原始图像中? 我希望只能看到第一个矩形。
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]
在原始图像上创建视图 ,而不是新对象。 修改该视图将修改基础原始图像。 有关更多详细信息,请参见http://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html 。
您可以通过在裁剪时创建一个副本来解决此问题: crop = image[100:300,100:300].copy()
。
注意: image[100:300,100:300]
参数为y: y+h, x: x+w not x: x+w, y: y+h
如果要保存裁剪的图像,只需添加以下代码:
cv2.imwrite("Cropped.jpg", roi)
after cv2.imshow("Cropped", roi)
我希望这有帮助。
您可以使用轻松在python中裁剪图像
roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]]
为了得到两点,可以调用cv2.setMouseCallback("image", mouse_crop)
。 该功能是这样的
def mouse_crop(event, x, y, flags, param):
# grab references to the global variables
global x_start, y_start, x_end, y_end, cropping
# if the left mouse button was DOWN, start RECORDING
# (x, y) coordinates and indicate that cropping is being
if event == cv2.EVENT_LBUTTONDOWN:
x_start, y_start, x_end, y_end = x, y, x, y
cropping = True
# Mouse is Moving
elif event == cv2.EVENT_MOUSEMOVE:
if cropping == True:
x_end, y_end = x, y
# if the left mouse button was released
elif event == cv2.EVENT_LBUTTONUP:
# record the ending (x, y) coordinates
x_end, y_end = x, y
cropping = False # cropping is finished
refPoint = [(x_start, y_start), (x_end, y_end)]
if len(refPoint) == 2: #when two points were found
roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]]
cv2.imshow("Cropped", roi)
您可以从此处获取详细信息: 使用Python进行鼠标单击和裁剪
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.