在QLABEL上显示图片并画框‘
时间: 2023-12-22 20:04:10 浏览: 122
实现这个功能需要使用Python和一些相关的库,包括Qt和OpenCV。以下是一个简单的代码示例,可以在QLABEL上显示图像并绘制矩形框:
```python
from PyQt5.QtGui import QImage, QPixmap, QPainter, QPen
from PyQt5.QtCore import Qt, QPoint, QRect
from PyQt5.QtWidgets import QLabel
import cv2
class ImageLabel(QLabel):
def __init__(self):
super().__init__()
self.image = None
self.rect_start = None
self.rect_end = None
def set_image(self, image_path):
self.image = cv2.imread(image_path)
self.display_image()
def display_image(self):
height, width, channel = self.image.shape
bytesPerLine = 3 * width
qImg = QImage(self.image.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped()
pixmap = QPixmap.fromImage(qImg)
self.setPixmap(pixmap)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.rect_start = event.pos()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.rect_end = event.pos()
self.update()
def paintEvent(self, event):
super().paintEvent(event)
if self.rect_start and self.rect_end:
painter = QPainter(self)
painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
rect = QRect(self.rect_start, self.rect_end)
painter.drawRect(rect)
if __name__ == '__main__':
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
label = ImageLabel()
label.set_image('image.jpg')
label.show()
sys.exit(app.exec_())
```
在这个例子中,我们创建了一个名为`ImageLabel`的自定义QLabel类。我们重写了`set_image`方法来读取并显示图像,重写了`mousePressEvent`和`mouseReleaseEvent`方法来记录框的起点和终点,重写了`paintEvent`方法来绘制矩形框。
当我们运行这个代码示例时,它将显示一个名为`image.jpg`的图像,并且我们可以在图像上单击并拖动鼠标来绘制矩形框。
阅读全文