你可以轻松地使用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):
global x_start, y_start, x_end, y_end, cropping
if event == cv2.EVENT_LBUTTONDOWN:
x_start, y_start, x_end, y_end = x, y, x, y
cropping = True
elif event == cv2.EVENT_MOUSEMOVE:
if cropping == True:
x_end, y_end = x, y
elif event == cv2.EVENT_LBUTTONUP:
x_end, y_end = x, y
cropping = False
refPoint = [(x_start, y_start), (x_end, y_end)]
if len(refPoint) == 2:
roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]]
cv2.imshow("Cropped", roi)
cv2.imwrite("crop.jpg",roi)
您可以从这里获取详细信息:使用Python进行鼠标点击和裁剪
对于C++,您可以按照以下方式操作:
void mouse_call(int event,int x,int y,int,void*)
{
if(event==EVENT_LBUTTONDOWN)
{
leftDown=true;
cor1.x=x;
cor1.y=y;
cout <<"Corner 1: "<<cor1<<endl;
}
if(event==EVENT_LBUTTONUP)
{
if(abs(x-cor1.x)>20&&abs(y-cor1.y)>20)
{
leftup=true;
cor2.x=x;
cor2.y=y;
cout<<"Corner 2: "<<cor2<<endl;
}
else
{
cout<<"Select a region more than 20 pixels"<<endl;
}
}
if(leftDown==true&&leftup==false)
{
Point pt;
pt.x=x;
pt.y=y;
Mat temp_img=img.clone();
rectangle(temp_img,cor1,pt,Scalar(0,0,255));
imshow("Original",temp_img);
}
if(leftDown==true&&leftup==true)
{
box.width=abs(cor1.x-cor2.x);
box.height=abs(cor1.y-cor2.y);
box.x=min(cor1.x,cor2.x);
box.y=min(cor1.y,cor2.y);
Mat crop(img,box);
namedWindow("Cropped Image");
imshow("Cropped Image",crop);
leftDown=false;
leftup=false;
}
}
你可以从这里获取详细信息:
使用C++进行鼠标点击和裁剪。