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, width, height, byteValue, QtGui.QImage.Format_RGB888)
self.ui.imageView.setPixmap(QtGui.QPixmap.fromImage(qimage))
python类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, filename, '.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, 0, pmap.width(), pmap.height(), Qt.KeepAspectRatio)
self.show()
self.image_loaded = True
def savePascalVocFormat(self, filename, 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, 0, 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, width, height, bytesPerLine, QtGui.QImage.Format_RGB888)
if swapped:
qimage = qimage.rgbSwapped()
return qimage
#return QPixmap.fromImage(qimg)
def savePascalVocFormat(self, filename, 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, imgFileNameWithoutExt,
imageShape, 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[1], bndbox[2],
bndbox[3], label, 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 __init__(self, parent=None):
super(ImageModel, self).__init__(parent)
self.modelImage = QImage()
def setImage(self, image):
self.beginResetModel()
self.modelImage = QImage(image)
self.endResetModel()
def openImage(self, fileName):
image = QImage()
if image.load(fileName):
self.model.setImage(image)
if not fileName.startswith(':/'):
self.currentPath = fileName
self.setWindowTitle("%s - Pixelator" % self.currentPath)
self.printAction.setEnabled(True)
self.updateView()
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, width, 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_y, 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, 0)
cv2.convertScaleAbs(blur, blur, 2, 1)
# Combine the blurred with the sun
combo = cv2.addWeighted(blur, 0.5, npimage, 0.5, -1)
h, w, 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, 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_y, moon_z)
glFlush()
self.fbo.release()
def __init__(self, parent=None):
super(ImageModel, self).__init__(parent)
self.modelImage = QImage()
def setImage(self, image):
self.beginResetModel()
self.modelImage = QImage(image)
self.endResetModel()
def openImage(self, fileName):
image = QImage()
if image.load(fileName):
self.model.setImage(image)
if not fileName.startswith(':/'):
self.currentPath = fileName
self.setWindowTitle("%s - Pixelator" % self.currentPath)
self.printAction.setEnabled(True)
self.updateView()
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 set_image(cv_image, ui_element):
qimg = QtGui.QImage(cv_image, cv_image.shape[1], cv_image.shape[0], cv_image.strides[0], QtGui.QImage.Format_RGB888)
pixmap = QtGui.QPixmap(qimg)
pixmap = pixmap.scaledToHeight(ui_element.height())
ui_element.setPixmap(pixmap)
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, 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, 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()