[英]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.