def loadCached():
try:
# TODO, rework to use app cache directory
img = QtGui.QImage()
if img.load("/tmp/shader.png"):
newimg = img.convertToFormat(QtGui.QImage.Format.Format_ARGB32)
shape = newimg.height(), newimg.width()
ptr = newimg.constBits()
# Extract the first channel
data = numpy.array(ptr, dtype=numpy.uint8).reshape(newimg.height(), newimg.width(), 4)[:,:,0].copy()
st = json.load(open("/tmp/shader.json","r"))
atlas = {}
for k, v in list(st.items()):
atlas[k] = AtlasEntry(v['w'], v['h'], v['sx'], v['sy'], v['tx'], v['ty'], v['l'], v['t'], v['hb'])
return atlas, data
except IOError:
pass
return None
python类QImage()的实例源码
def __init__(self, templateData, parcelationData, axis, correlationTable, colorTable, selectedColor):
super(SliceViewer, self).__init__()
self.template = templateData
self.regionId = None
self.parcelation = parcelationData
self.axis = axis
self.CommunityMode = False
self.correlationTable = correlationTable
self.colorTable= colorTable
self.selectedColor = selectedColor
self.displayedSlice = 0
self.QImage = []
scalefactor = 350
self.scaleFactor = int(math.ceil(scalefactor / self.parcelation.shape[0]))
numColors = self.parcelation.max()
self.clut = np.zeros(numColors, dtype=np.uint32)
for i in range(numColors):
r, g, b = colorsys.hls_to_rgb(float(i) / float(numColors), 0.5, 1.0)
self.clut[i] = (255 << 24 | int(255*r) << 16 | int(255*g) << 8 | int(255*b))
slice_view_layout = QtGui.QHBoxLayout()
self.setLayout(slice_view_layout)
slider = QtGui.QSlider()
slider.setRange(0, self.template.shape[self.axis]-1)
slider.valueChanged.connect(self.setDisplayedSlice)
slider.sliderReleased.connect(self.handleSliderRelease)
slider.setValue(self.displayedSlice)
slice_view_layout.addWidget(slider)
self.label = QtGui.QLabel()
self.updateSliceLabel()
slice_view_layout.addWidget(self.label)
def updateSliceLabel(self):
image_slice = self.extractSlice(self.template)
image_data = (255 << 24 | image_slice << 16 | image_slice << 8 | image_slice)
self.TemplateImageData = image_data
parcelation_slice = self.extractParcelationSlice(self.parcelation)
indices = np.flatnonzero(parcelation_slice)
for idx in indices:
image_data.flat[idx] = self.clut[parcelation_slice.flat[idx]-1]
image_data = np.array(image_data[:, ::-1], order='F')
image = QtGui.QImage(image_data, image_data.shape[0], image_data.shape[1], QtGui.QImage.Format_ARGB32)
image = image.scaled(self.scaleFactor*image.width(), self.scaleFactor*image.height())
self.label.setPixmap(QtGui.QPixmap.fromImage(image))
def UpdateColors(self):
self.regenerateElectrodes(self.ElectrodeData.timeStep)
for node in self.NodeIds:
self.unselectNodes(node)
try:
temp = self.ElectrodeData.graphWidget.partition[node.counter]
except IndexError:
temp = 0
if self.ElectrodeData.ScalarSize:
Size = eval('self.ElectrodeData.graphWidget.'+self.ElectrodeData.electrodeSizeFactor+'[node.counter-1]')
node.setNodeSize(Size,self.ElectrodeData.electrodeSizeFactor)
else:
Size = 0.4
node.setNodeSize(Size,"nothing to Display")
if not(self.ElectrodeData.nodeSizeFactor == 1):
node.ScalarNodeSize(self.ElectrodeData.nodeSizeFactor)
if self.ElectrodeData.Glyph:
for node in self.NodeIds:
node.setGlyph(True)
if self.ElectrodeData.ElectrodeScreenshot:
pixmap = QtGui.QImage(self.scene.sceneRect().size().toSize())
pAin = QtGui.QPainter(pixmap)
self.scene.render(pAin,QtCore.QRectF(self.width/4+50, self.height/4+50, 3*self.width/6,3*self.height/6))
fileName = str("Time_"+str(self.ElectrodeData.timeStep)+"_Syllable_"+str(self.ElectrodeData.syllableUnit)+"_Alg_"+str(self.ElectrodeData.clusterActivated)+".png")
pixmap1 = QtGui.QPixmap.fromImage(pixmap)
def create_shelf():
"""
Create the OBB shelf
Raises:
None
Returns:
None
"""
tab_layout = mel.eval('$pytmp=$gShelfTopLevel')
shelf_exists = cmds.shelfLayout('OBB', exists=True)
if shelf_exists:
cmds.deleteUI('OBB', layout=True)
shelf = cmds.shelfLayout('OBB', parent=tab_layout)
for button, kwargs in buttons.items():
img = QtGui.QImage(kwargs['image'])
kwargs['width'] = img.width()
kwargs['height'] = img.height()
cmds.shelfButton(label=button, parent=shelf, **kwargs)
# Fix object 0 error.
shelves = cmds.shelfTabLayout(tab_layout, query=True, tabLabelIndex=True)
for index, shelf in enumerate(shelves):
cmds.optionVar(stringValue=("shelfName%d" % (index+1), str(shelf)))
def set_icon(self, icon_path, icon):
if icon_path:
icon_path = utils.path_join(self.project_dir(), icon_path)
if os.path.exists(icon_path):
if icon_path.endswith('.icns'):
pngs = pngs_from_icns(icon_path)
if pngs:
ba = QtCore.QByteArray(pngs[-1].data)
image = QtGui.QImage.fromData(ba, 'PNG')
else:
return
else:
image = QtGui.QImage(icon_path)
if image.width() >= image.height():
image = image.scaledToWidth(48,
QtCore.Qt.SmoothTransformation)
else:
image = image.scaledToHeight(48,
QtCore.Qt.SmoothTransformation)
icon.setPixmap(QtGui.QPixmap.fromImage(image))
icon.setStyleSheet('')
else:
icon.setPixmap(None)
icon.setStyleSheet(self.icon_style)
else:
icon.setPixmap(None)
icon.setStyleSheet(self.icon_style)
def __init__(self):
super(NodeView,self).__init__()
self._scene = OPScene()
# Obsolete
self.nodeList = list()
# Variables
self.clickedItem = None
self.itemMode = None # Define which item is selected
self.mousePositionX = 0
self.mousePositionY = 0
self.mode = None
# Configure QGraphics View
self.setSceneRect(0, 0, -1, -1)
self.setFocusPolicy(QtCore.Qt.ClickFocus)
self.setMouseTracking(True)
self.setRenderHints(QtGui.QPainter.Antialiasing)
self.setViewportUpdateMode(QtGui.QGraphicsView.FullViewportUpdate)
# Init QGraphic Scene
self.sc = QtGui.QGraphicsScene()
self.setScene(self.sc)
self.sceneScale = 0.7
# Paint the background
brush = QtGui.QBrush()
brush.setTransform(QtGui.QTransform().scale(0.75, 0.75))
brush.setTextureImage(QtGui.QImage("/Users/draknova/Documents/workspace/sPipe/bin/images/gridTexture.jpg"))
self.sc.setBackgroundBrush(brush)
######################
####### EVENTS #######
######################
### KEYBOARD EVENTS ##
def create_data_img(size):
img = QImage(size, size, QImage.Format_ARGB32)
img.fill(0)
return img
def create_index_img(size=32):
img = QImage(size, size, QImage.Format_ARGB32)
# fill the image with empty color
img.fill(0)
return img
def showImg(self,label,img):
if len(img.shape) == 2:
img = cv2.applyColorMap(img, cv2.COLORMAP_JET)
img = cv2.resize(img, (512, 512),cv2.INTER_AREA)
height, width, byteValue = img.shape
byteValue = byteValue * width
timg = img.copy()
image = QtGui.QImage(timg.data, width, height,byteValue, QtGui.QImage.Format_RGB888)
label.setPixmap(QtGui.QPixmap(image).scaled(label.size(),aspectMode=QtCore.Qt.KeepAspectRatio))
""" visualize function from
https://github.com/BVLC/caffe/blob/master/examples/00-classification.ipynb
"""
def vis_square(self, data):
"""Take an array of shape (n, height, width) or (n, height, width, 3)
and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)"""
print "Data Shape : ", data.shape
# normalize data for display
data = (data - data.min()) / (data.max() - data.min())
# force the number of filters to be square
n = int(np.ceil(np.sqrt(data.shape[0])))
padding = (((0, n ** 2 - data.shape[0]),
(0, 1), (0, 1)) # add some space between filters
+ ((0, 0),) * (data.ndim - 3)) # don't pad the last dimension (if there is one)
data = np.pad(data, padding, mode='constant', constant_values=0) # pad with ones (white)
# tile the filters into an image
data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
# show at display
#print 'Data shape : ', data.shape , len(data.shape)
img = 255 * data
img = cv2.resize(img, (512, 512))
img = np.array(img, dtype='uint8')
img_c = cv2.applyColorMap(img, cv2.COLORMAP_JET)
height, width, byteValue = img_c.shape
byteValue = byteValue * width
self.image = QtGui.QImage(img_c.data, width, height, byteValue, QtGui.QImage.Format_RGB888)
self.ui.labelDisplay.setPixmap(QtGui.QPixmap(self.image))
def chat_image_view_ui(self, button):
if not button.img_path:
return
# make widjet
ui_path = G.MW.chat_img_viewer_path
# widget
loader = QtUiTools.QUiLoader()
file = QtCore.QFile(ui_path)
#file.open(QtCore.QFile.ReadOnly)
img_window = G.MW.chatImgViewer = loader.load(file, G.MW)
file.close()
# SHOW IMAGE
image = QtGui.QImage(button.img_path)
img_window.setWindowTitle(button.img_path)
img_window.image_label.setBackgroundRole(QtGui.QPalette.Base)
img_window.image_label.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
img_window.image_label.setScaledContents(True)
img_window.image_label.setPixmap(QtGui.QPixmap.fromImage(image))
# connect button
img_window.cansel_button.clicked.connect(partial(G.MW.close_window, img_window))
img_window.show()
def tm_make_preview_ui(self):
self.makePreviewDialog = QtGui.QDialog(self)
self.makePreviewDialog.setModal(True)
#self.makePreviewDialog.resize(300, 300)
self.makePreviewDialog.setWindowTitle(('Make Preview: /// ' + self.current_task['asset']))
# add widgets
v_layout = QtGui.QVBoxLayout()
# -- image Label
self.makePreviewDialog.imageLabel = QtGui.QLabel()
self.makePreviewDialog.imageLabel.setFixedSize(300,300)
v_layout.addWidget(self.makePreviewDialog.imageLabel)
# -- button
h__layout = QtGui.QHBoxLayout()
button_frame = QtGui.QFrame(parent = self.makePreviewDialog)
cansel_button = QtGui.QPushButton('Cansel', parent = button_frame)
h__layout.addWidget(cansel_button)
paste_button = QtGui.QPushButton('Paste', parent = button_frame)
h__layout.addWidget(paste_button)
save_button = QtGui.QPushButton('Save', parent = button_frame)
h__layout.addWidget(save_button)
button_frame.setLayout(h__layout)
v_layout.addWidget(button_frame)
self.makePreviewDialog.setLayout(v_layout)
# connect buttons
cansel_button.clicked.connect(partial(self.close_window, self.makePreviewDialog))
paste_button.clicked.connect(partial(self.tm_paste_image_from_clipboard, self.makePreviewDialog.imageLabel))
save_button.clicked.connect(partial(self.tm_save_preview_image_action, self.makePreviewDialog))
# -- load img to label
img_path = os.path.join(self.db_chat.preview_img_path, (self.current_task['asset'] + '.png'))
if not os.path.exists(img_path):
self.makePreviewDialog.imageLabel.setText('No Image')
else:
image = QtGui.QImage(img_path)
self.makePreviewDialog.imageLabel.setPixmap(QtGui.QPixmap.fromImage(image))
self.makePreviewDialog.show()
def tm_paste_image_from_clipboard(self, img_label):
rand = hex(random.randint(0, 1000000000)).replace('0x', '')
img_path = os.path.normpath(os.path.join(self.db_chat.tmp_folder, ('tmp_image_' + rand + '.png')))
clipboard = QtGui.QApplication.clipboard()
img = clipboard.image()
if img:
img.save(img_path)
cmd = '%s %s -resize 300 %s' % (os.path.normpath(self.db_chat.convert_exe), img_path, img_path)
cmd2 = '%s %s -resize 300x300 %s' % (os.path.normpath(self.db_chat.convert_exe), img_path, img_path)
cmd3 = '\"%s\" \"%s\" -resize 300 \"%s\"' % (os.path.normpath(self.db_chat.convert_exe), img_path, img_path)
print(cmd)
print(cmd2)
print(cmd3)
try:
os.system(cmd)
except:
try:
os.system(cmd2)
except:
try:
os.system(cmd3)
except:
return(False, 'in tm_paste_image_from_clipboard - problems with conversion resize.png')
else:
self.message('Cannot Image!', 2)
return(False, 'Cannot Image!')
image = QtGui.QImage(img_path)
img_label.setPixmap(QtGui.QPixmap.fromImage(image))
self.makePreviewDialog.img_path = img_path
def tm_save_preview_image_action(self, window):
# self.preview_img_path
if not os.path.exists(self.db_chat.preview_img_path):
try:
os.mkdir(self.db_chat.preview_img_path)
except:
print(self.db_chat.preview_img_path)
# copyfile
save_path = os.path.join(self.db_chat.preview_img_path, (self.current_task['asset'] + '.png'))
icon_path = os.path.join(self.db_chat.preview_img_path, (self.current_task['asset'] + '_icon.png'))
tmp_icon_path = window.img_path.replace('.png','_icon.png')
# -- copy
shutil.copyfile(window.img_path, save_path)
# -- resize
cmd = '%s %s -resize 100 %s' % (os.path.normpath(self.db_chat.convert_exe), window.img_path, tmp_icon_path)
cmd2 = '%s %s -resize 100x100 %s' % (os.path.normpath(self.db_chat.convert_exe), window.img_path, tmp_icon_path)
cmd3 = '\"%s\" \"%s\" -resize 100 \"%s\"' % (os.path.normpath(self.db_chat.convert_exe), window.img_path, tmp_icon_path)
try:
os.system(cmd)
except:
try:
os.system(cmd2)
except:
try:
os.system(cmd3)
except:
self.message('problems with conversion _icon.png', 2)
return(False, 'in tm_save_preview_image_action - problems with conversion resize.png')
shutil.copyfile(tmp_icon_path, icon_path)
# load to preview image_label
image = QtGui.QImage(save_path)
self.myWidget.image_label.setPixmap(QtGui.QPixmap.fromImage(image))
self.close_window(window)
# ------ show tz ------------
def imageCallback(self,data):
if self.save_image:
filename = self.datapath + os.sep +"log" + self.camera_name + ".jpg"
img = cv_bridge.CvBridge().imgmsg_to_cv2(data, "bgr8")
cv2.imwrite(filename,img)
rospy.loginfo("Saved Image %s"%filename)
self.save_image = False
format = QtGui.QImage.Format_ARGB32
try:
self.updateCalled.emit(QtGui.QImage(data.data, data.width, data.height, format))
except Exception,e:
print e
def showWordCloud(self):
wordcloud = WordCloud(width=800, height=400).generate(self.fullText)
img = np.array(wordcloud.to_image())
height, width, byteValue = img.shape
byteValue = byteValue * width
image = QtGui.QImage(img.data, width, height, byteValue, QtGui.QImage.Format_RGB888)
pxmp = QtGui.QPixmap(image)
self.label.setPixmap(pxmp)
def __init__(self, media, parent):
super(ImageMediaView, self).__init__(media, parent)
self._widget = QLabel(parent)
self._widget.setGeometry(media['_geometry'])
self._img = QImage()
self.set_default_widget_prop()
def chat_image_view_ui(self, button):
if not button.img_path:
return
# make widjet
ui_path = G.MW.chat_img_viewer_path
# widget
loader = QtUiTools.QUiLoader()
file = QtCore.QFile(ui_path)
#file.open(QtCore.QFile.ReadOnly)
img_window = G.MW.chatImgViewer = loader.load(file, G.MW)
file.close()
# SHOW IMAGE
image = QtGui.QImage(button.img_path)
img_window.setWindowTitle(button.img_path)
img_window.image_label.setBackgroundRole(QtGui.QPalette.Base)
img_window.image_label.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
img_window.image_label.setScaledContents(True)
img_window.image_label.setPixmap(QtGui.QPixmap.fromImage(image))
# connect button
img_window.cansel_button.clicked.connect(partial(G.MW.close_window, img_window))
img_window.show()
def QImage_from_numpy(arr):
shape = arr.shape
if len(shape) == 2:
channels = 1
elif len(shape) == 3:
channels = shape[3]
shape = shape[:2]
else:
raise ValueError("Shape of input array is whacko")
assert channels in [1,3,4]
assert arr.dtype == numpy.uint8
if channels != 4:
new_arr = numpy.zeros(tuple(shape) + (4,), dtype = numpy.uint8)
if channels > 1:
new_arr[:,:,:channels] = arr
else:
new_arr[:,:,:3] = arr[:,:, numpy.newaxis]
new_arr[:,:,3].fill(0xFF)
arr = new_arr
img = QtGui.QImage(arr.data, shape[1], shape[0], QtGui.QImage.Format_ARGB32)
img.array_holder = arr
return img
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(), frame.shape[1], frame.shape[0], 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 AddWidgets(self):
im = self.dataProcess.im
draw = ImageDraw.Draw(im)
self.setSizePolicy(QtGui.QSizePolicy.Policy.Expanding, QtGui.QSizePolicy.Policy.Expanding)
# Saving the image file as an output file
self.label = QtGui.QLabel()
self.NodeSlider()
im.save("BackgroundImage/output.png")
# Loading the pixmap for better analysis
loadedImage = QtGui.QImage()
loadedImage.load("BackgroundImage/output.png")
self.PixMap = QtGui.QPixmap.fromImage(loadedImage)
self.ElectrodeView = ElectrodeView(self)
x_interval = LayoutWidth/6
y_interval = LayoutHeight/6
for i in range(self.Chunks+1):
self.SmallMultipleElectrode.append(ElectrodeView(self, i, x_interval,y_interval))
CommunitySelectPerTime = QtCore.Signal(list, int ,list, list)
self.SmallMultipleElectrode[i].CommunitySelectPerTime.connect(self.SelectingCommunitiesInaTimestep)
self.SmallMultipleElectrode[i].DataLink.connect(self.GettingDataFromSmallMultiples)
self.SmallMultipleElectrode[i].CommunitySelectAcrossTime.connect(self.SelectingCommunitiesAcrossaTimestep)
self.LayoutForSmallMultiples = LayoutForSmallMultiples(self,self.SmallMultipleElectrode,x_interval,y_interval)
# # Use pycharm to have a better way to do it
self.ImageView = QtGui.QHBoxLayout()
self.ImageView2 = QtGui.QHBoxLayout()
self.ImageView2.setContentsMargins(0, 0, 0, 0)
self.ImageView2.addWidget(self.ElectrodeView)
self.ImageView2.setContentsMargins(0, 0, 0, 0)
# Image additions
vbox = QtGui.QVBoxLayout()
vbox.setContentsMargins(0, 0, 0, 0)
vbox.addLayout(self.ImageView2)
vbox.setContentsMargins(0, 0, 0, 0)
self.scene = QtGui.QGraphicsScene(0, 0,500 ,600)
self.setContentsMargins(0, 0, 0, 0)
self.setLayout(vbox)