Python PyQt5.QtGui 模块,QImage() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt5.QtGui.QImage()。
def selectimage(self, index):
if index >= len(self.files) or index < 0:
self.ui.imageView.setText("No images found.")
return
self.index = index
self.image = cv2.imread(self.files[index], 1)
image = self.modes[self.current_mode].getimage()
if len(image.shape) < 3 or image.shape[2] == 1:
image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
else:
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
height, width, byteValue = self.image.shape
byteValue = byteValue * width
qimage = QtGui.QImage(image, height, byteValue, QtGui.QImage.Format_RGB888)
self.ui.imageView.setpixmap(QtGui.Qpixmap.fromImage(qimage))
def QImagetoMat(qimg):
"""RGB888"""
#qimg = QImage()
#qimg.load("/home/auss/Pictures/test.png")
qimg = qimg.convertToFormat(QImage.Format_RGB888)
qimg = qimg.rgbSwapped()
#assert(qimg.byteCount() == qimg.width() * qimg.height() * 3)
ptr = qimg.constBits()
ptr.setsize(qimg.byteCount())
mat = np.array(ptr).reshape( qimg.height(), qimg.width(), 3) # copies the data
return mat
def __init__(self, refresh_signal, conflict_tags_message_dict, case_data_manager, *args, **kwargs):
super().__init__(*args, **kwargs)
self.refresh_signal = refresh_signal
self.case_data_manager = case_data_manager
ui_dir_path = os.path.dirname(__file__)
ui_file_path = os.path.join(ui_dir_path, "conflict_tag.ui")
uic.loadUi(ui_file_path, self)
self.setwindowTitle("conflict tag")
self.conflict_tags_message_dict = conflict_tags_message_dict
self.set_conflict_tags_table_widget()
config = Config()
image = QImage(os.path.join(config.images, 'notice.png'))
result = image.scaled(40, 40)
self.notice_image_label.setpixmap(Qpixmap.fromImage(result))
self.notice_image_label.setAlignment(Qt.AlignCenter)
self.notice_text_label.setText(
'?????????\n'
'1???????????????????????????????\n'
'2???????????????') # todo ??????
self.conflict_tags_submit_button.clicked.connect(self.conflict_tags_submit)
self.button_style(self.conflict_tags_submit_button)
self.cancel_submit_button.clicked.connect(self.cancel_submit)
self.button_style(self.cancel_submit_button)
def make_button(self, filename, tooltip, alignment=Qt.AlignCenter):
"""
Description: Creates a QLabel which will contain an image and will
simulate a button. No associated text will be shown.
Arguments: 1. filename: The filename of the icon/image to show
2. tooltip: Some text to show as a tooltip to the image
3. alignment: Alignment of the button (center by default)
Returns: The created QLabel button
"""
global STANDARDCELLCSS, IMGDIR
filepath = '%s%s%s' % (IMGDIR, '.png')
icon = QImage(filepath)
image = QLabel()
image.setToolTip('<span style="color:#B9B900">%s</span>' % (tooltip))
image.setStyleSheet(STANDARDCELLCSS)
image.setpixmap(Qpixmap.fromImage(icon))
image.setAlignment(alignment)
return image
def open_image_fd(self, dialog_text="Open Image", default_folder=""):
"""Opens a file dialog,allowing user to select an image file.
Creates a QImage object from the filename selected by the user in the
popup file dialog menu.
Args:
dialog_text [Optional(str.)]: Text to prompt user with in open file
dialog. Defaults to "Open Image".
default_folder [Optional(str.)]: Path of the default directory to open
the file dialog Box to. Defaults to "".
Returns:
QImage: Image object created from selected image file.
None: Returns None if no file was selected in the dialog Box.
"""
fname = QtWidgets.QFileDialog.getopenFileName(self, dialog_text, default_folder) # Todo: Filter to show only image files
if fname:
image = QtGui.QImage(fname[0])
else:
image = None
return image
def load_image(self, image):
"""
Call this to load a new image from the provide QImage into
this HomographyView's scene. The image's top left corner will
be placed at (0,0) in the scene.
"""
self.scene_image = image
new_scene = HomographyScene(self)
pmap = QtGui.Qpixmap().fromImage(image)
pmapitem = new_scene.addpixmap(pmap)
new_scene.register_pixmap(pmapitem)
new_scene.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(0, 0, 0)))
self.setScene(new_scene)
self.fitInView(0, pmap.width(), pmap.height(), Qt.KeepAspectRatio)
self.show()
self.image_loaded = True
def savePascalVocFormat(self, shapes, imagePath, imageData,
lineColor=None, fillColor=None, databaseSrc=None):
imgFolderPath = os.path.dirname(imagePath)
imgFolderName = os.path.split(imgFolderPath)[-1]
imgFileName = os.path.basename(imagePath)
#imgFileNameWithoutExt = os.path.splitext(imgFileName)[0]
# Read from file path because self.imageData might be empty if saving to
# Pascal format
image = QImage()
image.load(imagePath)
imageShape = [image.height(), image.width(),
1 if image.isGrayscale() else 3]
writer = PascalVocWriter(imgFolderName, imgFileName,
imageShape, localImgPath=imagePath)
writer.verified = self.verified
for shape in shapes:
points = shape['points']
label = shape['label']
# Add Chris
difficult = int(shape['difficult'])
bndBox = LabelFile.convertPoints2BndBox(points)
writer.addbndBox(bndBox[0], bndBox[1], bndBox[2], bndBox[3], label, difficult)
writer.save(targetFile=filename)
return
def saveImage(self, fname): # noqa: N802
"""
Saves current viewport as a png file of the given fname.
"""
rect = self.viewport()
rgb = QtGui.QImage.Format_RGB32
image = QtGui.QImage(rect.width(), rect.height(), rgb)
image.fill(QtGui.QColor(255, 255, 255))
painter = QtGui.QPainter(image)
self.render(painter)
if not image.save(fname):
raise ValueError('Could not save image %s' % fname)
del painter
def getIcon(self):
icon = (
'0000010001001010000001002000680400001600000028000000100000002000000001'
'0020000000000000040000130b0000130b00000000000000000000000000000773e600'
'0577df000877dd060477df490277e0a70277e0e30277e0fb0277e0fb0277e0e30277e0'
'a70377e0490577e0060377e1000175f00000000000000000000377e0000577df180377'
'e0920277e0ed0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0277e0ed02'
'77e0920377e1180277e100000000000577df000577df180277e0b10177e0ff0177e0ff'
'0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0277e0'
'b10377e1180377e1000174de070176df920076e0ff0077e0ff0177e0ff0177e0ff0177'
'e0ff0076e0ff0076e0ff0177e0ff0177e0ff0177e0ff0077e0ff0076e0ff0176e09202'
'76e107127fe0481983e2ee1f87e3ff0d7de1ff0076e0ff0077e0ff067ae1ff1d86e3ff'
'1a84e3ff077ae1ff0177e0ff0076e0ff0e7ee1ff1e87e3ff1581e2ee0a7be1483592e4'
'a759a6e9ff4fa0e8ff66adeaff1e86e3ff0b7ce1ff60a9e9ff57a5e9ff56a4e9ff459b'
'e7ff0277e0ff288ce4ff68aeeaff51a1e8ff56a4e8ff2389e3a70578e0e40177e0ff00'
'72dfff499de7ff4fa1e8ff3c96e6ff53a3e8ff0074dfff0075e0ff0579e0ff0478e0ff'
'6cb0ebff268be4ff0075e0ff0378e0ff0478e0e40176e0fb1481e2ff439ae7ff7bb8ec'
'ff2a8ce4ff5da8eaff63abeaff3793e5ff3894e6ff3392e5ff1481e2ff73b4edff0b7c'
'e1ff0177e0ff0177e0ff0277e0fb2c8de4fb76b5ecff50a1e8ff1e86e3ff0075e0ff59'
'a6e9ff63abeaff3692e5ff3793e5ff76b5ecff2389e3ff73b4ecff0d7de1ff0077e0ff'
'0077e0ff0177e0fb5ea8e9e455a4e8ff0075e0ff0b7ce1ff0679e0ff3090e5ff59a6e9'
'ff0377e0ff1380e2ff62abe9ff0c7ce1ff65aceaff3693e5ff0478e0ff0d7de1ff077a'
'e1e42489e2a75ba7e9ff59a5e9ff5aa6e9ff1983e2ff0578e0ff489de7ff5da8eaff5f'
'a9eaff2c8ee4ff0075e0ff1a84e2ff60aaeaff5ba6e9ff57a4e9ff1f86e3a70075df48'
'0478e0ee0e7ee1ff087be1ff0177e0ff0177e0ff0177e0ff0c7de1ff087be1ff0076e0'
'ff0177e0ff0076e0ff0479e0ff0e7ee1ff087ae1ee0377e0480777de070377e0920177'
'e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff01'
'77e0ff0177e0ff0177e0ff0277e0920477e1070577df000577df180277e0b10177e0ff'
'0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0'
'ff0277e0b10377e1180377e100000000000377e0000577df180377e0920277e0ed0177'
'e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0277e0ed0277e0920377e11802'
'77e10000000000000000000773e6000577df000877dd060477df490277e0a70277e0e3'
'0277e0fb0277e0fb0277e0e30277e0a70377e0490676e0060377e1000174f300000000'
'00e0070000c00300008001000000000000000000000000000000000000000000000000'
'00000000000000000000000000000000000080010000c0030000e0070000')
image = QtGui.QImage()
image.loadFromData(QtCore.QByteArray.fromHex(icon))
pixmap = QtGui.Qpixmap()
pixmap.convertFromImage(image)
return QtGui.QIcon(pixmap)
def mkQImage(argb, alpha=None, trans=False):
"""
Use the cpoied data of ARGB argb to make QImage and return it.
argb: (w,h,3 or 4) this (bgr/rgb or bgra/rgba).
alpha: ARGB32 if alpha is True else RGB32 (always be 4).
trans: if trans is true then x/y axes are transposed.
In default
Qt: ARGB (32bpp),(width,height)
"""
if alpha is None or not isinstance(alpha,bool):
alpha = (argb.shape[2] == 4)
if argb.shape[2] == 3:
tmp = np.empty(argb.shape[:2] + (4,), dtype = argb.dtype)
tmp[...,:3] = argb
tmp[...,3] = 255
argb = tmp
if alpha:
imgFormat = QtGui.QImage.Format_ARGB32
else:
imgFormat = QtGui.QImage.Format_RGB32
if trans:
# (y,x,c) => (x,y,c)
argb = argb.transpose((1, 2))
addr = argb.data #addr = memoryview(argb)
qimg = QtGui.QImage(addr,argb.shape[1],argb.shape[0],imgFormat)
return qimg
def MatToQImage(mat,swapped=True):
'''?numpy.ndarray???QtGui.QImage?????Qpixmap?????QLabel???'''
height, width = mat.shape[:2]
dim = 1 if mat.ndim == 2 else mat.shape[2]
bytesPerLine = dim * width
# ?numpy.ndarray???QtGui.QImage????????
qimage = QtGui.QImage(mat.data, bytesPerLine, QtGui.QImage.Format_RGB888)
if swapped:
qimage = qimage.rgbSwapped()
return qimage
#return Qpixmap.fromImage(qimg)
def savePascalVocFormat(self, databaseSrc=None):
imgFolderPath = os.path.dirname(imagePath)
imgFolderName = os.path.split(imgFolderPath)[-1]
imgFileName = os.path.basename(imagePath)
imgFileNameWithoutExt = os.path.splitext(imgFileName)[0]
# Read from file path because self.imageData might be empty if saving to
# Pascal format
image = QImage()
image.load(imagePath)
imageShape = [image.height(), imgFileNameWithoutExt, localImgPath=imagePath)
writer.verified = self.verified
for shape in shapes:
points = shape['points']
label = shape['label']
# Add Chris
difficult = int(shape['difficult'])
direction = shape['direction']
isRotated = shape['isRotated']
# if shape is normal Box,save as bounding Box
# print('direction is %lf' % direction)
if not isRotated:
bndBox = LabelFile.convertPoints2BndBox(points)
writer.addbndBox(bndBox[0],
bndBox[3], difficult)
else: #if shape is rotated Box,save as rotated bounding Box
robndBox = LabelFile.convertPoints2RotatedbndBox(shape)
writer.addRotatedbndBox(robndBox[0],robndBox[1],
robndBox[2],robndBox[3],robndBox[4],label,difficult)
writer.save(targetFile=filename)
return
def reload_image(self):
if not self.goals.events and not self.force_refresh:
return
self.force_refresh = False
save(self.goals, self.db)
if self.use_dot:
with open('work.dot', 'w') as f:
f.write(dot_export(self.goals))
run(['dot', '-Tpng', '-o', 'work.png', 'work.dot'])
img = QImage('work.png')
self.label.setpixmap(Qpixmap.fromImage(img))
self.label.resize(img.size().width(), img.size().height())
def setimage(self, image):
self.beginResetModel()
self.modelImage = QImage(image)
self.endResetModel()
def loadFromMemory(self):
""" This slot function is called in the second Dialog process,when the
user presses the "Load Image from Shared Memory" button. First,it
attaches the process to the shared memory segment created by the first
Dialog process. Then it locks the segment for exclusive access,copies
the image data from the segment into a QBuffer,and streams the QBuffer
into a QImage. Then it unlocks the shared memory segment,detaches
from it,and finally displays the QImage in the Dialog.
"""
if not self.sharedMemory.attach():
self.ui.label.setText(
"Unable to attach to shared memory segment.\nLoad an "
"image first.")
return
buf = QBuffer()
ins = QDataStream(buf)
image = QImage()
self.sharedMemory.lock()
buf.setData(self.sharedMemory.constData())
buf.open(QBuffer.ReadOnly)
ins >> image
self.sharedMemory.unlock()
self.sharedMemory.detach()
self.ui.label.setpixmap(Qpixmap.fromImage(image))
def changeIcon(self):
icon = QIcon()
for row in range(self.imagesTable.rowCount()):
item0 = self.imagesTable.item(row, 0)
item1 = self.imagesTable.item(row, 1)
item2 = self.imagesTable.item(row, 2)
if item0.checkState() == Qt.Checked:
if item1.text() == "normal":
mode = QIcon.normal
elif item1.text() == "Active":
mode = QIcon.Active
elif item1.text() == "disabled":
mode = QIcon.disabled
else:
mode = QIcon.Selected
if item2.text() == "On":
state = QIcon.On
else:
state = QIcon.Off
fileName = item0.data(Qt.UserRole)
image = QImage(fileName)
if not image.isNull():
icon.addpixmap(Qpixmap.fromImage(image), mode, state)
self.previewArea.setIcon(icon)
def qimage_to_numpy(image):
# Convert a QImage to a numpy array
image = image.convertToFormat(QtGui.QImage.Format_ARGB32)
width = image.width()
height = image.height()
ptr = image.constBits()
return np.frombuffer(ptr.asstring(image.byteCount()), dtype=np.uint8).reshape(height, 4)
def paintGL(self, sun_x, sun_y, sun_z, moon_x, moon_y, moon_z):
# Draw the sun
self.fbo.bind()
self.draw_sun(sun_x, sun_z)
glFlush()
self.fbo.release()
image = self.fbo.toImage()
# Produce blurred image of sun
npimage = qimage_to_numpy(image)
h, w, b = npimage.shape
blur = cv2.GaussianBlur(npimage, (75, 75), 0)
cv2.convertScaleAbs(blur, blur, 2, 1)
# Combine the blurred with the sun
combo = cv2.addWeighted(blur, 0.5, npimage, -1)
h, b = combo.shape
qimage = QtGui.QImage(combo.data,w,h,QtGui.QImage.Format_ARGB32).rgbSwapped()
self.fbo.bind()
device = QtGui.QOpenGLPaintDevice(RES_X, RES_Y)
painter = QtGui.QPainter()
painter.begin(device)
rect = QtCore.QRect(0, RES_X, RES_Y)
# Draw the blurred sun/sun combo image on the screen
painter.drawImage(rect, qimage, rect)
painter.end()
self.fbo.release()
# Draw the moon
self.fbo.bind()
self.draw_moon(moon_x, moon_z)
glFlush()
self.fbo.release()
def setimage(self, image):
self.beginResetModel()
self.modelImage = QImage(image)
self.endResetModel()
def loadFromMemory(self):
""" This slot function is called in the second Dialog process,and finally displays the QImage in the Dialog.
"""
if not self.sharedMemory.attach():
self.ui.label.setText(
"Unable to attach to shared memory segment.\nLoad an "
"image first.")
return
buf = QBuffer()
ins = QDataStream(buf)
image = QImage()
self.sharedMemory.lock()
buf.setData(self.sharedMemory.constData())
buf.open(QBuffer.ReadOnly)
ins >> image
self.sharedMemory.unlock()
self.sharedMemory.detach()
self.ui.label.setpixmap(Qpixmap.fromImage(image))
def changeIcon(self):
icon = QIcon()
for row in range(self.imagesTable.rowCount()):
item0 = self.imagesTable.item(row, state)
self.previewArea.setIcon(icon)
def fill_screen_cap(self):
# Todo: Screen 2 shows black image
slider_left = self.ui.slider_left.value()
slider_right = self.ui.slider_right.value()
slider_top = self.ui.slider_top.value()
slider_bottom = self.ui.slider_bottom.value()
frame_raw = ImageGrab.grab(bBox=functions.get_screen_bBox())
frame = np.uint8(frame_raw)
frame = cv2.rectangle(frame, (slider_left, slider_top), (slider_right, slider_bottom), (255, 0), 4)
qimg = QtGui.QImage(frame, frame.shape[1], frame.shape[0], frame.strides[0], QtGui.QImage.Format_RGB888)
pixmap = QtGui.Qpixmap(qimg)
pixmap = pixmap.scaledToHeight(self.ui.screen_cap.height())
self.ui.screen_cap.setpixmap(pixmap)
def _draw_spectrogram(self, painter, _event):
width = painter.viewport().width()
height = (1 << DERIVATION_SIZE) + 1
pixels = np.zeros([width, height], dtype='byte')
horizontal_res = (
self._api.opt.general['audio']['spectrogram_resolution'])
# since the task queue is a LIFO queue,in order to render the columns
# left-to-right,they need to be iterated backwards (hence reversed()).
for x in reversed(range(width)):
pts = self._pts_from_x(x)
pts = (pts // horizontal_res) * horizontal_res
column = self._spectrum_cache.get(pts, NOT_CACHED)
if column is NOT_CACHED:
self._spectrum_provider.schedule_task(pts)
self._spectrum_cache[pts] = CACHING
continue
if column is CACHING:
continue
pixels[x] = column
pixels = pixels.transpose().copy()
image = QtGui.QImage(
pixels.data,
pixels.shape[1],
pixels.shape[0],
pixels.strides[0],
QtGui.QImage.Format_Indexed8)
image.setColorTable(self._color_table)
painter.save()
painter.scale(1, painter.viewport().height() / (height - 1))
painter.drawpixmap(0, QtGui.Qpixmap.fromImage(image))
painter.restore()
def load_emojis(self):
async with aiohttp.ClientSession(loop=self.app.loop) as session:
for emoji in self.app.client.get_all_emojis():
if emoji.server == self.memo.server:
with timeout(10):
async with session.get(emoji.url) as response:
img = await response.read()
qmg = QImage()
qmg.loadFromData(img)
self.userOutput.document().addResource(QTextDocument.ImageResource, QUrl(emoji.url), qmg)
def _stopCamera(self):
if self._image_reply:
self._image_reply.abort()
self._image_reply.downloadProgress.disconnect(self._onStreamDownloadProgress)
self._image_reply = None
image_request = None
self._stream_buffer = b""
self._stream_buffer_start_index = -1
self._camera_image = QImage()
self.newImage.emit()
def homography_open_image_camera(self):
"""Opens a file dialog,allowing user to select an camera image file.
Creates a QImage object from the filename of an camera image
selected by the user in a popup file dialog menu.
"""
qi = self.open_image_fd(dialog_text="Select camera image...")
if qi:
self.ui.homography_cameraview.load_image(qi)
def homography_open_image_aerial(self):
"""Opens a file dialog,allowing user to select an aerial image file.
Creates a QImage object from the filename of an aerial image
selected by the user in a popup file dialog menu.
"""
qi = self.open_image_fd(dialog_text="Select aerial image...")
if qi:
self.ui.homography_aerialview.load_image(qi)
def load_image(self,0) in the scene.
"""
self.scene_image = image
new_scene = QtWidgets.QGraphicsScene(self)
pmap = QtGui.Qpixmap().fromImage(image)
pmapitem = new_scene.addpixmap(pmap)
new_scene.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(0, Qt.KeepAspectRatio)
self.show()
self.image_loaded = True
def load_image_from_path(self, path):
im = QtGui.QImage(path)
self.load_image(im)
def get_qimage(self, image: np.ndarray):
height, colors = image.shape
bytesPerLine = 3 * width
QImage = QtGui.QImage
image = QImage(image.data,
width,
height,
bytesPerLine,
QImage.Format_RGB888)
image = image.rgbSwapped()
return image
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawImage(0, self.image)
self.image = QtGui.QImage()
def get_qimage(self,
QImage.Format_RGB888)
image = image.rgbSwapped()
return image
def setimage(self, image):
self.beginResetModel()
self.modelImage = QImage(image)
self.endResetModel()
def loadFromMemory(self):
""" This slot function is called in the second Dialog process,and finally displays the QImage in the Dialog.
"""
if not self.sharedMemory.attach():
self.ui.label.setText(
"Unable to attach to shared memory segment.\nLoad an "
"image first.")
return
buf = QBuffer()
ins = QDataStream(buf)
image = QImage()
self.sharedMemory.lock()
buf.setData(self.sharedMemory.constData())
buf.open(QBuffer.ReadOnly)
ins >> image
self.sharedMemory.unlock()
self.sharedMemory.detach()
self.ui.label.setpixmap(Qpixmap.fromImage(image))
def changeIcon(self):
icon = QIcon()
for row in range(self.imagesTable.rowCount()):
item0 = self.imagesTable.item(row, state)
self.previewArea.setIcon(icon)
def init_ui(self):
# v.Box
gBox = QtWidgets.qgridLayout()
Box = QtWidgets.QVBoxLayout()
self.rBox = QtWidgets.QVBoxLayout()
self.hBox = QtWidgets.QHBoxLayout()
# padding/margins
gBox.setContentsMargins(0, 0)
self.rBox.setContentsMargins(0, 10, 10)
self.hBox.setContentsMargins(0, 10)
Box.addStretch()
self.hBox.addStretch()
gBox.setSpacing(10)
Box.setSpacing(0)
self.rBox.setSpacing(5)
self.hBox.setSpacing(0)
image = QtGui.QImage()
image.loadFromData(urllib.request.urlopen('http://i.imgur.com/04DUqa3.png').read())
png = QLabel(self)
pixmap = QtGui.Qpixmap(image)
png.setpixmap(pixmap)
gBox.addWidget(png, 1, Qt.AlignTop)
Box.insertSpacing(1, 10)
self.l1 = QLabel(self)
self.l1.setWordWrap(True)
self.large_font.setBold(True)
self.l1.setFont(self.large_font)
Box.addWidget(self.l1, Qt.AlignTop)
hline = QtWidgets.qframe()
hline.setFrameShape(QtWidgets.qframe.HLine)
hline.setFrameShadow(QtWidgets.qframe.Sunken)
gBox.addWidget(hline, 3, Qt.AlignBottom)
# start form
self.req_ui()
self.rBox.setAlignment(Qt.AlignTop)
Box.addLayout(self.rBox, 1)
gBox.addLayout(Box, 2)
gBox.addLayout(self.hBox, 3)
self.setLayout(gBox)
# window
self.setFixedSize(490, 400)
self.setwindowIcon(QtGui.QIcon('red.ico'))
self.setwindowTitle('Red discord Bot - Setup')
self.show()
def preview_image_file(self, path):
filename = path.split('/')[-1]
if self.graphics_preview is None:
msg = "Graphics preview widget not created yet."
logger.critical(msg)
return
if not self.isVisible():
msg = "Preview widget invisible,not previewing image."
logger.info(msg)
return
self.setCurrentWidget(self.graphics_preview)
scene = QtWidgets.QGraphicsScene(self)
self.graphics_preview.setScene(scene)
# Using QImage instead of directly creating the Qpixmap
# prevents a segmentation fault in my container setup
image = QtGui.QImage(path)
if image.isNull():
fmt = "File '{}' should be an image,but isn't."
msg = fmt.format(filename)
logger.error(msg)
return
pixmap = QtGui.Qpixmap.fromImage(image)
if pixmap.isNull():
fmt = "Failed to generate pixmap from image '{}'."
msg = fmt.format(filename)
logger.critical(msg)
return
pixmap_item = QtWidgets.QGraphicspixmapItem(pixmap)
scene.addItem(pixmap_item)
self.graphics_preview.fitInView(
pixmap_item,
Qt.Qt.KeepAspectRatio,
)
fmt = "Previewed file '{}' as an image."
msg = fmt.format(filename)
logger.info(msg)
def handleSignals(self, signal, param):
if signal == 'Input.OnInputRequested':
self.showInputDialog()
print("Text sending")
if signal == 'Player.OnStop':
self.isPlaying = False
self.status.setText( 'nothing playing Now' )
self.img.setpixmap(Qpixmap(IMG_PATH))
if self.timer.isActive():
self.timer.stop()
self.pbar.setValue(0)
print('Stoping timer')
if signal == 'play':
self.isPlaying = True
self.status.setText( param )
self.rpc("Player.GetItem",{"properties":["thumbnail","fanart"],"playerid":1}, True)
if not self.timer.isActive():
self.timer.start(1000, self)
print('Starting timer')
if signal == 'queue':
gui.rpc("GUI.ShowNotification",{"title":"Added to playlist!", "message":param}, False)
if signal == 'System.OnQuit' or signal == 'System.OnRestart':
if self.timer.isActive():
self.timer.stop()
print('Stoping timer')
self.quit(False)
if signal == 'thumbnail':
url = urllib.parse.unquote(param)
try:
img_arr = urllib.request.urlopen(url).read()
qImg = QImage()
qImg.loadFromData(img_arr)
self.img.setpixmap(Qpixmap(qImg))
except Exception as e:
print("---> Error while getting image: %s" % e)
if signal == 'time':
tokens = param.split('-',1)
curTime = int(tokens[0])
tottime = int(tokens[1])
if tottime>0:
self.pbar.setValue((curTime/tottime)*100)
if signal == 'addons':
OpenDialog(param, self).exec_()
#print (signal)
def startCapture(self):
global currentSecond
global delayVideoData
#cap = self.capturer
num = 0
while(self.capturing):
while (self.paused and self.capturing):
time.sleep(0.05)
prevTime = datetime.Now()
if (self.frameNumberChanged):
newFrameNumber = int(self.sliderVideoFrame.value()*30)
num = newFrameNumber
self.frameNumber = newFrameNumber
self.frameNumberChanged = False
frame = self.videoReader.get_data(num)
num = num+1
if (num >= self.videoReader.get_length()):
self.frameNumberChanged=True
self.sliderVideoFrame.setValue(0)
self.start_button.setText('Start')
self.video_thread = False
self.capturing = False
break
self.frameNumber = num
currentSecond = self.frameNumber/fps #valor importante para sync datos
self.labelCurrentVideoSecond.setText("{0:.1f}".format(currentSecond - delayVideoToData))
if (self.sliderWasReleased):
self.sliderVideoFrame.setValue(int(self.frameNumber/fps))
#Convert opencv mat to QImage:
imageQ = QtGui.QImage(frame.tostring(), QtGui.QImage.Format_RGB888)
if (frame.shape[1] != videowidthShow or frame.shape[0] != videoheightShow):
imageQ = imageQ.scaled(videowidthShow, videoheightShow) #resize image to fit
#Convert QImage to pixmap:
pixmap = QtGui.Qpixmap.fromImage(imageQ)
#Set pixmap to label:
#self.labelImage.setpixmap(pixmap) #old mode,cuidado porque es un thread outside the GUI,esto da problemas en pyqt
self.signalUpdatepixmap.emit(pixmap) #nuevo mode para evitar esos problemas
self.updatescoreLabels()
diftime = ((datetime.Now()-prevTime).microseconds)/1000000.0
#print (diftime)
#print(1/fps - diftime )
if (diftime < 1/fps):
time.sleep (1/fps - diftime)
else:
time.sleep(0.01)
app.processEvents() #prevents app from crashing because of lack of responsiveness
def __init__(self,args,parent=None):
QtGui.QMainWindow.__init__(self,parent)
self.srclist=[] # list of source directories
self.imageIndex=0 # index of selected image
self.seriesMap=OrderedDict() # maps series table row tuples to DicomSeries object it was generated from
self.seriesColumns=list(seriesListColumns) # keywords for columns
self.selectedRow=-1 # selected series row
self.lastDir='.' # last loaded directory root
self.filterRegex='' # regular expression to filter tags by
# create the directory queue and loading thread objects
self.dirQueue=Queue() # queue of directories to load
self.loadDirThread=threading.Thread(target=self._loadDirsThread)
self.loadDirThread.daemon=True # clean shutdown possible with daemon threads
self.loadDirThread.start() # start the thread Now,it will wait until something is put on self.dirQueue
# setup ui
self.setupUi(self) # create UI elements based on the loaded .ui file
self.setwindowTitle('Dicombrowser v%s (FOR RESEARCH ONLY)'%(__version__))
self.setStatus('')
# connect signals
self.importButton.clicked.connect(self._openDirDialog)
self.statusSignal.connect(self.setStatus)
self.updateSignal.connect(self._updateSeriesTable)
self.filterLine.textChanged.connect(self._setFilterString)
self.imageSlider.valueChanged.connect(self.setSeriesImage)
self.seriesView.clicked.connect(self._seriesTableClicked)
# setup the list and table models
self.srcmodel=QStringListModel()
self.seriesmodel=SeriesTableModel(self.seriesColumns)
self.seriesmodel.layoutChanged.connect(self._seriesTableResize)
self.tagmodel=QtGui.QStandardItemmodel()
# assign models to views
self.sourceListView.setModel(self.srcmodel)
self.seriesView.setModel(self.seriesmodel)
self.tagView.setModel(self.tagmodel)
# create the pyqtgraph object for viewing images
self.imageview=pg.ImageView()
layout=QtGui.qgridLayout(self.view2DGroup)
layout.addWidget(self.imageview)
# load the empty image placeholder into a ndarray
qimg=QtGui.QImage(':/icons/noimage.png')
bytedata=qimg.constBits().asstring(qimg.width()*qimg.height())
self.noimg=np.ndarray((qimg.width(),qimg.height()),dtype=np.ubyte,buffer=bytedata)
# add the directories passed as arguments to the directory queue to start loading
for i in args:
if os.path.isdir(i):
self.addSourceDir(i)
def render_image(self, rect, image_path, dpm, quality, bg_color, autocrop):
"""Render a section of self.scene to an image.
It is assumed that all input arguments are valid.
Args:
rect (Rect): The part of the document to render,
in document coordinates.
image_path (str): The path to the output image.
This must be a valid path relative to the current
working directory.
dpm (int): The pixels per meter of the rendered image.
quality (int): The quality of the output image for compressed
image formats. Must be either `-1` (default compression) or
between `0` (most compressed) and `100` (least compressed).
bg_color (Color): The background color for the image.
autocrop (bool): Whether or not to crop the output image to tightly
fit the contents of the frame. If true,the image will be
cropped such that all 4 edges have at least one pixel not of
`bg_color`.
Returns: None
Raises:
ImageExportError: If Qt image export fails for unkNown reasons.
"""
scale_factor = dpm / Unit(Meter(1)).value
pix_width = Unit(rect.width).value * scale_factor
pix_height = Unit(rect.height).value * scale_factor
q_image = QtGui.QImage(pix_width, pix_height,
QtGui.QImage.Format_ARGB32)
q_image.setDotsPerMeterX(dpm)
q_image.setDotsPerMeterY(dpm)
q_color = color_to_q_color(bg_color)
q_image.fill(q_color)
painter = QtGui.QPainter()
painter.begin(q_image)
target_rect = QtCore.QRectF(q_image.rect())
source_rect = rect_to_qt_rect_f(rect)
self.scene.render(painter, target=target_rect, source=source_rect)
painter.end()
if autocrop:
q_image = images.autocrop(q_image, q_color)
success = q_image.save(image_path, quality=quality)
if not success:
raise ImageExportError(
'UnkNown error occurred when exporting image to ' + image_path)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。