QT开发中文网

使用QImage预测后怎么添加样本采集

如果你希望在使用QImage进行预测后添加样本采集,可以根据以下示例代码进行修改:

import sys
import cv2
from PySide6.QtCore import Qt
from PySide6.QtGui import QImage, QPixmap
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Sample Collection")
        self.setFixedSize(800, 600)

        self.image_label = QLabel(self)
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setFixedSize(640, 480)
        
        self.capture_button = QPushButton("Capture", self)
        self.capture_button.setGeometry(350, 520, 100, 40)
        self.capture_button.clicked.connect(self.capture_sample)

    def capture_sample(self):
        image = self.image_label.pixmap().toImage()

        # 将QImage转换回OpenCV图像
        width = image.width()
        height = image.height()
        
        ptr = image.bits()
        ptr.setsize(image.byteCount())
        
         # 使用NumPy从QImage数据中创建OpenCV图像(BGR格式)
         cv_image_bgr = np.array(ptr).reshape(height, width, 4)[:, :, :3]
         
         # 进行目标检测预测或其他操作,例如使用YOLOv8模型
        
         # 假设获取到了目标检测结果
         detections = [{'class_name': 'person', 'bbox': (100, 100, 200, 200)},
                       {'class_name': 'car', 'bbox': (300, 300, 150, 80)}]

         for detection in detections:
             class_name = detection['class_name']
             bbox = detection['bbox']  # (x, y, width, height)

             x, y, w, h = bbox
             cv2.rectangle(cv_image_bgr , (x, y), (x+w, y+h), (255, 0, 0), 2)
             cv2.putText(cv_image_bgr , class_name, (x, y-10),
                         cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0 ,0), 2)

            # 将样本图像保存到指定位置(这里仅作示例,可以根据需要自定义保存格式和路径)
            sample_file = f"{class_name}_{x}_{y}.jpg"
            cv2.imwrite(sample_file, cv_image_bgr[y:y+h,x:x+w])

        # 将BGR格式的图像转换为RGBA格式以便显示在界面上
        cv_image_rgba = cv2.cvtColor(cv_image_bgr , cv2.COLOR_BGR2RGBA)
        
        q_image_with_annotation = QImage(cv_image_rgba.data,
                                         width,
                                         height,
                                         QImage.Format_RGBA8888)
                                         
        self.image_label.setPixmap(QPixmap.fromImage(q_image_with_annotation))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

在这个修改后的示例代码中,我们使用NumPy从QImage数据中创建OpenCV图像,并进行目标检测预测或其他操作。假设我们获取到了目标检测结果,并在图像上绘制了边界框和类别信息。然后,将感兴趣区域截取下来,并保存为样本图像。

请注意,这里仅提供了简单的保存方式,你可以根据实际需求自定义保存格式和路径。

希望这对你有所帮助!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=9167

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?