基于python 您所在的位置:网站首页 鼠标如何画直线 基于python

基于python

2024-07-03 21:36| 来源: 网络整理| 查看: 265

做项目越来越感觉到需要学的东西很多,但完成之后又觉得随着时间流逝,很多东西又变得模糊甚至是完全遗忘,所以在此进行记录与梳理。参考的会放在下方的链接里

 

首先是实现图片显示鼠标移动的痕迹(左键按下后),然后倾斜矫正

 

先看效果图(画线的时候,线是随着鼠标的位置实时演示,能够看到自己画的线)

 

画矩形时需要将对应的cv.line改成cv.rectangle即可,填上对应point1或point2和当前坐标即可

 

 

线代码段:

import cv2 as cv import numpy as np import math global img global point1, point2 global average def on_mouse(event, x, y, flag, param): global img, point1, point2, average img2 = img.copy() if event == cv.EVENT_LBUTTONDOWN: #左键点击 point1 = (x,y) cv.circle(img2, point1, 10, (0,255,0), 5) cv.imshow('image', img2) elif event == cv.EVENT_MOUSEMOVE and (flag & cv.EVENT_FLAG_LBUTTON): #按住左键拖曳 cv.line(img2, point1, (x,y), (255,0,0), 2) cv.imshow('image', img2) elif event == cv.EVENT_LBUTTONUP: #左键释放 point2 = (x,y) cv.line(img2, point1, point2, (0,0,255), 5) cv.imshow('image', img2) #反正切,此处简化,需要考虑除数为0的情况 average = math.atan((point1[1] - point2[1]) / (point1[0] - point2[0])) img = cv.imread('10.png') #此处更改图片路径 img = cv.resize(img, (540, 540), interpolation=cv.INTER_LINEAR)#改变了一下大小 cv.namedWindow('image') cv.setMouseCallback('image', on_mouse) cv.imshow('image', img) cv.waitKey(0) the_angel = int(average * 180 / np.pi) rows, cols ,n= img.shape #需要理解旋转的角度,近似在图像中心进行旋转 M = cv.getRotationMatrix2D((cols / 2, rows / 2), (the_angel+90), 1) dst = cv.warpAffine(img, M, (cols, rows)) cv.imshow('image1', dst) cv.waitKey(0) cv.imwrite("10_result.png",dst)#保存结果 cv.destroyAllWindows()

矩形代码段:

import cv2 as cv import numpy as np def nothing(args): pass global img global point1, point2 global min_x,min_y,width,height def on_mouse(event, x, y, flags, param): global img, point1, point2 global min_x ,min_y ,width, height img2 = img.copy() if event == cv.EVENT_LBUTTONDOWN: #左键点击 point1 = (x,y) cv.circle(img2, point1, 10, (0,255,0), 5) cv.imshow('image', img2) elif event == cv.EVENT_MOUSEMOVE and (flags & cv.EVENT_FLAG_LBUTTON): #按住左键拖曳 cv.rectangle(img2, point1, (x,y), (255,0,0), 2) cv.imshow('image', img2) elif event == cv.EVENT_LBUTTONUP: #左键释放 point2 = (x,y) cv.rectangle(img2, point1, point2, (0,0,255), 5) cv.imshow('image', img2) min_x = min(point1[0],point2[0]) min_y = min(point1[1],point2[1]) width = abs(point1[0] - point2[0]) height = abs(point1[1] -point2[1]) cut_img = img[min_y:min_y+height, min_x:min_x+width] cv.imwrite('part_10.jpg', cut_img) img = cv.imread('10.png') img = cv.resize(img, (540, 540), interpolation=cv.INTER_LINEAR) cv.namedWindow('image') cv.setMouseCallback('image', on_mouse) cv.imshow('image', img) cv.waitKey(0)

参考:https://docs.opencv.org/3.4/da/d6e/tutorial_py_geometric_transformations.html(官网)

https://www.jb51.net/article/167369.htm

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有