我正在尝试使用OpenCV从磁盘加载.jpg
或.png
图像,并将其显示在我的GUI中的QLable
中。我做了所有调整大小和从BGR转换为RGB的东西。有时我会得到一个完美的结果:
有时我会得到垃圾:
以下是此示例的代码:
from PyQt4.QtGui import QApplication, QWidget, QVBoxLayout, QImage, QPixmap, QLabel, QPushButton, QFileDialog
import cv2
app = QApplication([])
window = QWidget()
layout = QVBoxLayout(window)
window.setLayout(layout)
display = QLabel()
display.setMinimumSize(600, 400)
layout.addWidget(display)
button = QPushButton('Load', window)
layout.addWidget(button)
def read_image():
path = QFileDialog.getOpenFileName(window)
if path:
picture = cv2.imread(path)
if picture is not None:
scaling_factor = min(display.width()/picture.shape[1], display.height()/picture.shape[0])
width = round(picture.shape[1] * scaling_factor)
height = round(picture.shape[0] * scaling_factor)
picture = cv2.resize(picture, (width, height))
print(path, scaling_factor, picture.shape)
image = QImage(picture.tobytes(), # The content of the image
picture.shape[1], # The width (number of columns)
picture.shape[0], # The height (number of rows)
QImage.Format_RGB888) # The image is stored in 3*8-bit format
display.setPixmap(QPixmap.fromImage(image.rgbSwapped()))
else:
display.setPixmap(QPixmap())
button.clicked.connect(read_image)
window.show()
app.exec()
答案 0 :(得分:0)
我认为问题在于图像的大小和调整大小的图像的大小。如果图片的大小不能被(宽、高)整除,图片将无法正确显示。我也有类似的问题here。OpenCV的step是size_t,当你把图片转成QImage的时候需要转成int。
image = QImage(picture.tobytes(), # The content of the image
picture.shape[1], # The width (number of columns)
picture.shape[0], # The height (number of rows)
static_cast<int>(picture.step), # cast width step to int
QImage.Format_RGB888) # The image is stored in 3*8-bit format