打开一张图片后能使用鼠标在上面绘画的代码
时间: 2024-05-05 15:18:53 浏览: 13
以下是使用Python的OpenCV和PyQt5库实现的代码:
```python
import cv2
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow
from PyQt5.QtGui import QPixmap, QPainter, QPen
from PyQt5.QtCore import Qt, QPoint
class PaintLabel(QLabel):
def __init__(self, parent=None):
super().__init__(parent)
self.last_point = QPoint()
self.current_point = QPoint()
self.drawing = False
self.image = None
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.last_point = event.pos()
self.drawing = True
def mouseMoveEvent(self, event):
if (event.buttons() & Qt.LeftButton) and self.drawing:
self.current_point = event.pos()
self.draw()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.drawing = False
def draw(self):
painter = QPainter(self.pixmap())
pen = QPen(Qt.black, 2, Qt.SolidLine)
painter.setPen(pen)
painter.drawLine(self.last_point, self.current_point)
self.last_point = self.current_point
self.update()
def set_image(self, image):
self.image = image
self.setPixmap(QPixmap.fromImage(image))
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.label = PaintLabel()
self.setCentralWidget(self.label)
def set_image(self, image):
self.label.set_image(image)
if __name__ == '__main__':
app = QApplication(sys.argv)
image_path = 'test.jpg'
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
height, width, channel = image.shape
window = MainWindow()
window.set_window_title('Image Painter')
window.setFixedSize(width, height)
window.set_image(QImage(image.data, width, height, channel*width, QImage.Format_RGB888))
window.show()
sys.exit(app.exec_())
```
该代码使用QMainWindow和QLabel控件构建一个图形用户界面,显示指定的图片,并允许使用鼠标在图片上绘制线条。具体实现细节包括:
- 继承QLabel并覆盖其mousePressEvent、mouseMoveEvent和mouseReleaseEvent方法,响应鼠标事件并绘制线条。
- 创建一个QMainWindow实例,并在其中央设置一个PaintLabel实例。
- 调整窗口大小为图片大小,并在PaintLabel实例中显示指定的图片。
在使用时,只需指定要绘制的图片路径即可。注意要把图片格式转换成RGB模式,因为OpenCV默认使用BGR模式。运行后,会显示一个可以绘制的窗口,并在窗口标题中显示“Image Painter”字样。