def numpy_to_qpixmap(npimg): data = npimg.astype(np.uint8) (height, width) = npimg.shape[0:2] format_ = QtGui.QImage.Format_RGB888 qimg = QtGui.QImage(data, width, height, format_) qpixmap = QtGui.QPixmap.fromImage(qimg) return qpixmap
def paint(self, painter, option, index): painter.fillRect(option.rect, QtGui.QColor(191, 222, 185)) # path = "path\to\my\image.jpg" self.path = "image.bmp" image = QtGui.QImage(str(self.path)) pixmap = QtGui.QPixmap.fromImage(image) pixmap.scaled(50, 40, QtCore.Qt.KeepAspectRatio) painter.drawPixmap(option.rect, pixmap)
def read_thumb_as_qimg(thumb_path): r""" Args: thumb_path (?): Returns: tuple: (qimg, width, height) CommandLine: python -m guitool.api_thumb_delegate --test-read_thumb_as_qimg --show Example: >>> # ENABLE_DOCTEST >>> from guitool.api_thumb_delegate import * # NOQA >>> import guitool >>> # build test data >>> thumb_path = ut.grab_test_imgpath('carl.jpg') >>> # execute function >>> guitool.ensure_qtapp() >>> (qimg) = ut.memprof(read_thumb_as_qimg)(thumb_path) >>> if ut.show_was_requested(): >>> lbl = test_show_qimg(qimg) >>> guitool.qtapp_loop() >>> # verify results >>> print(qimg) Timeit:: %timeit np.dstack((npimg, np.full(npimg.shape[0:2], 255, dtype=np.uint8))) %timeit cv2.cvtColor(npimg, cv2.COLOR_BGR2BGRA) npimg1 = np.dstack((npimg, np.full(npimg.shape[0:2], 255, dtype=np.uint8))) # seems to be memory leak in cvtColor? npimg2 = cv2.cvtColor(npimg, cv2.COLOR_BGR2BGRA) """ if VERBOSE_THUMB: print('[ThumbDelegate] Reading thumb as qimg. thumb_path=%r' % (thumb_path,)) # Read thumbnail image and convert to 32bit aligned for Qt #if False: # data = np.dstack((npimg, np.full(npimg.shape[0:2], 255, dtype=np.uint8))) #if False: # # Reading the npimage and then handing it off to Qt causes a memory # # leak. The numpy array probably is never unallocated because qt doesn't # # own it and it never loses its reference count # #npimg = vt.imread(thumb_path, delete_if_corrupted=True) # #print('npimg.dtype = %r, %r' % (npimg.shape, npimg.dtype)) # #npimg = cv2.cvtColor(npimg, cv2.COLOR_BGR2BGRA) # #format_ = QtGui.QImage.Format_ARGB32 # ## #data = npimg.astype(np.uint8) # ## #npimg = np.dstack((npimg[:, :, 3], npimg[:, :, 0:2])) # ## #data = npimg.astype(np.uint8) # ##else: # ## Memory seems to be no freed by the QImage? # ##data = np.ascontiguousarray(npimg[:, :, ::-1].astype(np.uint8), dtype=np.uint8) # ##data = np.ascontiguousarray(npimg[:, :, :].astype(np.uint8), dtype=np.uint8) # #data = npimg # ##format_ = QtGui.QImage.Format_RGB888 # #(height, width) = data.shape[0:2] # #qimg = QtGui.QImage(data, width, height, format_) # #del npimg # #del data #else: #format_ = QtGui.QImage.Format_ARGB32 #qimg = QtGui.QImage(thumb_path, format_) qimg = QtGui.QImage(thumb_path) return qimg