def convertToGray(image): grayImg = QImage(image.size(), QImage.Format_ARGB32) for i in range(image.width()): for j in range(image.height()): rgb = image.pixel(i, j) gray = qGray(rgb) alpha = qAlpha(rgb) grayPixel = qRgba(gray, gray, gray, alpha) grayImg.setPixel(i, j, grayPixel) return grayImg
def setThemeEditorDatas(editor, themeDatas, pixmap, screenRect): textRect = themeTextRect(themeDatas, screenRect) x, y, width, height = themeEditorGeometry(themeDatas, textRect) editor.setGeometry(x, y, width, height) # p = editor.palette() ##p.setBrush(QPalette.Base, QBrush(pixmap.copy(x, y, width, height))) # p.setBrush(QPalette.Base, QColor(Qt.transparent)) # p.setColor(QPalette.Text, QColor(themeDatas["Text/Color"])) # p.setColor(QPalette.Highlight, QColor(themeDatas["Text/Color"])) # p.setColor(QPalette.HighlightedText, Qt.black if qGray(QColor(themeDatas["Text/Color"]).rgb()) > 127 else Qt.white) # editor.setPalette(p) editor.setAttribute(Qt.WA_NoSystemBackground, True) bf = getThemeBlockFormat(themeDatas) editor.setDefaultBlockFormat(bf) # b = editor.document().firstBlock() # cursor = editor.textCursor() # cursor.setBlockFormat(bf) # while b.isValid(): # bf2 = b.blockFormat() # bf2.merge(bf) # cursor.setPosition(b.position()) ##cursor.setPosition(b.position(), QTextCursor.KeepAnchor) # cursor.setBlockFormat(bf2) # b = b.next() editor.setTabStopWidth(themeDatas["Spacings/TabWidth"]) editor.document().setIndentWidth(themeDatas["Spacings/TabWidth"]) editor.highlighter.setMisspelledColor(QColor(themeDatas["Text/Misspelled"])) cf = QTextCharFormat() # f = QFont() # f.fromString(themeDatas["Text/Font"]) # cf.setFont(f) editor.highlighter.setDefaultCharFormat(cf) f = QFont() f.fromString(themeDatas["Text/Font"]) # editor.setFont(f) editor.setStyleSheet(""" background: transparent; color: {foreground}; font-family: {ff}; font-size: {fs}; selection-color: {sc}; selection-background-color: {sbc}; """.format( foreground=themeDatas["Text/Color"], ff=f.family(), fs="{}pt".format(str(f.pointSize())), sc="black" if qGray(QColor(themeDatas["Text/Color"]).rgb()) > 127 else "white", sbc=themeDatas["Text/Color"], ) ) editor._fromTheme = True
def render(self, rend=True): if (rend): if (self.modeBtn.isChecked()): self.qsst.srctext = self.textEdit.toPlainText() self.qsst.loadVars() self.qsst.convertQss() self.setStyleSheet(self.qsst.qss) else: self.setStyleSheet('') for var, btn in self.dict.items(): if ("rgb" in btn.text()): t = btn.text().strip(r" rgba()") c = t.split(',') if (len(c) > 3): a = c[3] else: a = 255 color = QColor(r, g, b, a) else: color = QColor(btn.text()) s = '' if (qGray(color.rgb()) < 100): s += "color:white;" btn.setStyleSheet(s + "background:" + btn.text())
def chclr(self, var): c = QColor() cstr = self.sender().text() if cstr: c.setNamedColor(cstr) else: c.setNamedColor("white") color = QColorDialog.getColor(c, self, self.tr("color pick"), QColorDialog.ShowAlphaChannel) if color.isValid(): s = '' clrstr = color.name() if color.alpha() == 255: clrstr = color.name().upper() else: # 'rgba({},{},{},{})'.format(color.red(), color.green(), color.blue(), color.alpha()) clrstr = color.name(QColor.HexArgb).upper() # s = 'font-size:8px;' if qGray(color.rgb()) < 100: s += 'color:white;' self.clrBtnDict[var].setText(clrstr) self.clrBtnDict[var].setStyleSheet(s + "background:" + clrstr) self.qsst.varDict[var] = clrstr self.qsst.writeVars() # 用setText之后undo redo堆栈全部消失,所以暂时用这种方法 pos = self.editor.verticalScrollBar().sliderPosition() self.editor.selectAll() self.editor.replaceSelectedText( self.qsst.srctext) # setText(self.qsst.srctext) # self.CodeEditor.setCursorPosition(xp,yp) self.editor.verticalScrollBar().setSliderPosition(pos) self.renderStyle()
def pixmap_into_gray_matrix(self, pixmap: QPixmap) -> np.ndarray: matrix = np.empty(shape=(config.IMG_WIDTH, config.IMG_HEIGHT)) image: QImage = pixmap.toImage() for i in range(pixmap.width()): for j in range(pixmap.height()): matrix[i][j] = 255 - qGray(image.pixel(i, j)) return matrix
def loadColorPanel(self): self.qsst.srctext = self.editor.text() self.qsst.loadVars() # item = self.colorGridLayout.itemAt(0) # while (item != None): # self.colorGridLayout.removeItem(item) # # self.colorGridLayout.removeWidget(item.widget()) # # item.widget().setParent(None)#这三行没有作用 # sip.delete(item.widget()) # 虽然控件删除了,但是grid的行数列数没减少,但是不影响使用 # sip.delete(item) # item = self.colorGridLayout.itemAt(0) # self.colorGridLayout.update() # 不起作用 # a,b=list(self.clrBtnDict.keys()),list(self.qsst.varDict.keys());a.sort();b.sort() if sorted(list(self.clrBtnDict.keys())) != sorted( list(self.qsst.varDict.keys())): while self.colorPanelLayout.count() > 0: self.colorPanelLayout.removeItem( self.colorPanelLayout.itemAt(0)) self.clrBtnDict = {} for varName, clrStr in self.qsst.varDict.items(): contianerWidget = QWidget() contianerWidget.setMinimumSize(QSize(185, 25)) label = QLabel(varName, contianerWidget) btn = QPushButton(clrStr, contianerWidget) if sys.platform.startswith("win"): font1 = QFont("Arial", 10, QFont.Medium) font2 = QFont("sans-serif", 9, QFont.Medium) label.setFont(font1) btn.setFont(font2) self.clrBtnDict[varName] = btn # label.setFixedWidth(80) # btn.setFixedWidth(100) label.move(5, 5) btn.move(100, 5) self.colorPanelLayout.addWidget(contianerWidget) self.colorPanelLayout.setSpacing(5) btn.clicked.connect(lambda x, var=varName: self.chclr(var)) for varName, btn in self.clrBtnDict.items(): clrStr = self.qsst.varDict[varName] btn.setText(clrStr) if "rgb" in clrStr: t = clrStr.strip(r" rgba()") c = t.split(',') if len(c) > 3: lable = c[3] else: lable = 255 color = QColor(c[0], c[1], c[2], lable) else: color = QColor(clrStr) s = '' if qGray(color.rgb()) < 100: s += "color:white;" else: s += "color:black;" btn.setStyleSheet(s + "background:" + btn.text())
def save(self): filePath, _ = QFileDialog.getSaveFileName(self, "Save Image", "", "PNG(*.png);;JPEG(*.jpg *.jpeg);;TIFF(*.tif *.tiff);;ALL FILES(*.*)") if filePath == "": return saveImg = self.maskQimage.convertToFormat(QImage.Format_Grayscale8).scaled(self.originalWidth,self.originalHeight) qimgHeight = saveImg.height() qimgWidth = saveImg.width() for rowIndex in range(qimgHeight): for colIndex in range(qimgWidth): pixVal = qGray(saveImg.pixel(colIndex,rowIndex)) if pixVal > 0: saveImg.setPixelColor(colIndex,rowIndex,QColor(1,1,1)) pixVal = qGray(saveImg.pixel(colIndex, rowIndex)) saveImg.save(filePath)
def grayScale(self, image): for i in range(self.w): for j in range(self.h): c = image.pixel(i, j) gray = qGray(c) alpha = qAlpha(c) image.setPixel(i, j, qRgba(gray, gray, gray, alpha)) return image
def disabledSideBarIcon(enabledicon: QPixmap) -> QPixmap: im = enabledicon.toImage().convertToFormat(QImage.Format_ARGB32) for y in range(im.height()): for x in range(im.width()): pixel = im.pixel(x, y) intensity = qGray(pixel) im.setPixel(x, y, qRgba(intensity, intensity, intensity, qAlpha(pixel))) return QPixmap.fromImage(im)
def toGray(image): w, h = (image.width(), image.height()) for x in xrange(w): for y in xrange(h): pixel = image.pixel(x, y) gray = qGray(pixel) alpha = qAlpha(pixel) image.setPixel(x, y, qRgba(gray, gray, gray, alpha)) return image
def addY(bitmap): nbmp = QImage(bitmap.width(), bitmap.height() + 1, bitmap.format()) nbmp.fill(0) for y in range(bitmap.height()): for x in range(bitmap.width()): data = qGray(bitmap.pixel(x, y)) if data: nbmp.setPixel(x, y, 1) return nbmp
def addY(bitmap): nbmp = QImage( bitmap.width(), bitmap.height() + 1, bitmap.format() ) nbmp.fill(0) for y in range( bitmap.height() ): for x in range( bitmap.width() ): data = qGray( bitmap.pixel( x, y ) ) if data: nbmp.setPixel( x, y, 1 ) return nbmp
def applyThreshold(self, image): minBrightness = self.parent.minBrightnessWalkify.value() maxBrightness = self.parent.maxBrightnessWalkify.value() if minBrightness != 0 or maxBrightness != 255: for x in range(image.width()): for y in range(image.height()): currcolor = qGray(image.pixel(x, y)) if currcolor <= minBrightness: image.setPixelColor(x, y, QColor(255, 255, 255)) if currcolor >= maxBrightness: image.setPixelColor(x, y, QColor(255, 255, 255))
def auto_find_bounds(self, image): histogram = [] bins = 256 for b in range(bins): histogram.append(0) for y in range(image.height()): for x in range(image.width()): gv = qGray(image.pixel(x, y)) histogram[gv] += 1 sections = 4 bounds = self.find_boundaries(sections, histogram, image) return bounds, sections
def make(self, image): """ the actual calculations, done on successive pixel positions popped from in self.reversed_pixel_order self.reversed_pixel_order was initialized with a call to discretize_lsystem() :param image: bitmap on wich to operate :return: """ self.removeOldGraphicsItems() if self.method == "Circles": methodhandler = CircleMethod(self.minBrightness, self.maxBrightness, self.minRadius, self.maxRadius, self.minStepSize, self.maxStepSize, self.clipToBitmap, self.strokeWidth, image.width(), image.height()) elif self.method == "Squiggles": methodhandler = SquiggleMethod(self.minBrightness, self.maxBrightness, self.strength, self.detail, self.minStepSize, self.maxStepSize, self.clipToBitmap, self.strokeWidth, image.width(), image.height()) else: assert False pos = self.reversed_pixel_order.pop() stepsize = 1 # visit the discretized lsystem positions while self.reversed_pixel_order: x = pos[0] y = pos[1] direction = pos[2] brightness = qGray(image.pixel(x, y)) if self.invertColors: brightness = 255 - brightness # handle the chosen method if self.minBrightness <= brightness <= self.maxBrightness: stepsize = methodhandler.step(x, y, direction, brightness) else: stepsize = methodhandler.skip(x, y, direction, brightness) # skip forward to next x,y coordinate for i in range(stepsize): if self.reversed_pixel_order: pos = self.reversed_pixel_order.pop() group = methodhandler.finish() self.addNewGraphicsItems(group)
def find_darkest(self, image): darkest_value = 256 darkest_x = 0 darkest_y = 0 half_radius = self.parent.reductionNeighborhoodWalkify.value() for x in range(half_radius, image.width() - half_radius, 1): for y in range(half_radius, image.height() - half_radius, 1): currcolor = qGray(image.pixel(x, y)) if currcolor < darkest_value: darkest_x = x darkest_y = y darkest_value = currcolor return darkest_x, darkest_y
def toBlackAndWhite(image): """ convenience method to convert a color image to b&w :param image: any image :return: b&w image """ newImage = QImage(image) for ii in range(newImage.width()): for jj in range(newImage.height()): gray = qGray(newImage.pixel(ii, jj)) newImage.setPixel(ii, jj, QColor(gray, gray, gray).rgb()) return newImage
def sendImage(self, image, x=50, y=50): print("sendImage") w = image.width() h = image.height() # TODO check size < max with/heigt wr = 8 * ((w + 7) // 8) # le = (wr * h) // 8 # send image information self.send_CMD_array([ 170, 22, 4, 2, 1, 80, int(x // 256), int(x % 256), int(y // 256), int(y % 256), int(wr // 256), int(wr % 256), int(h // 256), int(h % 256), 0, 0, int(le // 256), int(le % 256), int(w // 256), int(w % 256), 85 ]) time.sleep(1) # rezise image to wr *h with with pixel on right : img_big = image.scaled(QSize(wr, h)) img_big.fill(Qt.white) # miror every other line for l in range(h): for c in range(w): if l % 2: co = w - 1 - c else: co = c img_big.setPixel(co, l, image.pixel(c, l)) # transform image as bytearray byte_array = bytearray() for l in range(h): byte_temp = 0 for c in range(wr): if (c > 0) and not (c % 8): byte_array.append(byte_temp) byte_temp = 0 if qGray(img_big.pixel(c, l)) < 128: byte_temp += 1 << (7 - (c % 8)) byte_array.append(byte_temp) byte_array.append(85) self.transmit(byte_array, 8192)
def __render_icon_by_path_convert(path: str) -> QtGui.QIcon: ''' 返回灰度icon ''' icon = QtGui.QIcon() image = QtGui.QPixmap(path).toImage() for x in range(image.width()): for y in range(image.height()): color = image.pixel(x, y) gray = qGray(color) image.setPixel(x, y, qRgba(gray, gray, gray, qAlpha(color))) icon.addPixmap(QtGui.QPixmap.fromImage(image), QtGui.QIcon.Normal, QtGui.QIcon.On) return icon
def addX(bitmap, direction): if direction == 'left': x0 = 1 else: x0 = 0 size = QSize( bitmap.width() + 1, bitmap.height() ) new_bmp = QImage( size, bitmap.format() ) new_bmp.fill(0) for y in range( bitmap.height() ): for x in range( bitmap.width() ): data = qGray( bitmap.pixel( x, y ) ) if data: new_bmp.setPixel( x0 + x, y, 1 ) return new_bmp
def addX(bitmap, direction): if direction == 'left': x0 = 1 else: x0 = 0 size = QSize(bitmap.width() + 1, bitmap.height()) new_bmp = QImage(size, bitmap.format()) new_bmp.fill(0) for y in range(bitmap.height()): for x in range(bitmap.width()): data = qGray(bitmap.pixel(x, y)) if data: new_bmp.setPixel(x0 + x, y, 1) return new_bmp
def makeLines(self, image): # remove existing data on this layer self.removeOldGraphicsItems() group = QGraphicsItemGroup() sections = 4 coordinates = [] bounds = [ self.parent.region1Linify.value(), self.parent.region2Linify.value(), self.parent.region3Linify.value(), self.parent.region3Linify.value() ] for y in range(0, image.height(), 4): drawing = False for linetype in range(sections): if linetype >= 1: qt_y = y + linetype # / sections for x in range(image.width()): grayvalue = qGray(image.pixel(x, y)) start_drawing = (grayvalue < bounds[linetype]) and not drawing if start_drawing: coordinates.append([[x, qt_y]]) drawing = True stop_drawing = ((grayvalue >= bounds[linetype]) or (x == (image.width() - 1))) and drawing if stop_drawing: coordinates[-1].append([x, qt_y]) drawing = False group = QGraphicsItemGroup() for lineseg in coordinates: if len(lineseg) != 2 or len(lineseg[0]) != 2 or len( lineseg[1]) != 2: print("Unexpected lineseg: ", lineseg) else: lineitem = QGraphicsLineItem(lineseg[0][0], lineseg[0][1], lineseg[1][0], lineseg[1][1]) pen = QPen() pen.setWidth(1 / sections) lineitem.setPen(pen) group.addToGroup(lineitem) self.addNewGraphicsItems(group)
def grayScale(self): """ Public slot to convert the image to gray preserving transparency. """ cmd = IconEditCommand(self, self.tr("Convert to Grayscale"), self.__image) for x in range(self.__image.width()): for y in range(self.__image.height()): col = self.__image.pixel(x, y) if col != qRgba(0, 0, 0, 0): gray = qGray(col) self.__image.setPixel( x, y, qRgba(gray, gray, gray, qAlpha(col))) self.update() self.setDirty(True) self.__undoStack.push(cmd) cmd.setAfterImage(self.__image)
def grayScale(self): """ Public slot to convert the image to gray preserving transparency. """ cmd = IconEditCommand(self, self.tr("Convert to Grayscale"), self.__image) for x in range(self.__image.width()): for y in range(self.__image.height()): col = self.__image.pixel(x, y) if col != qRgba(0, 0, 0, 0): gray = qGray(col) self.__image.setPixel(x, y, qRgba(gray, gray, gray, qAlpha(col))) self.update() self.setDirty(True) self.__undoStack.push(cmd) cmd.setAfterImage(self.__image)
def process_frame(self, frame, levels): """ :param frame: :param levels: :return: """ histogram = [0.0] * levels if levels and frame.map(QAbstractVideoBuffer.ReadOnly): pixel_format = frame.pixelFormat() if pixel_format == QVideoFrame.Format_YUV420P or pixel_format == QVideoFrame.Format_NV12: # Process YUV data. bits = frame.bits() for idx in range(frame.height() * frame.width()): histogram[(bits[idx] * levels) >> 8] += 1.0 else: image_format = QVideoFrame.imageFormatFromPixelFormat( pixel_format) if image_format != QImage.Format_Invalid: # Process RGB data. image = QImage(frame.bits(), frame.width(), frame.height(), image_format) for y in range(image.height()): for x in range(image.width()): pixel = image.pixel(x, y) histogram[(qGray(pixel) * levels) >> 8] += 1.0 # Find the maximum value. max_value = 0.0 for value in histogram: if value > max_value: max_value = value # Normalise the values between 0 and 1. if max_value > 0.0: for i in range(len(histogram)): histogram[i] /= max_value frame.unmap() self.histogram_ready.emit(histogram)
def chclr(self, var): color = self.dlg.getColor(self.dlg.currentColor(), self, "color pick", QColorDialog.ShowAlphaChannel) if (color.isValid()): s = '' if (color.alpha() == 255): clrstr = color.name() else: clrstr = 'rgba({},{},{},{})'.format(color.red(), color.green(), color.blue(), color.alpha()) s = 'font-size:8px;' if (qGray(color.rgb()) < 100): s += 'color:white;' self.dict[var].setText(clrstr) self.dict[var].setStyleSheet(s + "background:" + clrstr) self.qsst.varDict[var] = clrstr self.qsst.writeVars() self.textEdit.setPlainText(self.qsst.srctext) self.render()
def buttonSave(self): experiment_name = params['experiment_name'] original_file_name = self.maskImgPath pat = re.compile( r'.+(xy\d{3,4})_(p\d{3,4})_.+') # supports 3- or 4-digit naming mat = pat.match(original_file_name) fovID = mat.groups()[0] peakID = mat.groups()[1] fileBaseName = '{}_{}_{}_t{:0=4}.tif'.format(experiment_name, fovID, peakID, self.frameIndex + 1) savePath = os.path.join(self.mask_dir, fileBaseName) # labelSavePath = os.path.join(params['seg_dir'],fileBaseName) print("Saved binary mask image as: ", savePath) if not os.path.isdir(self.mask_dir): os.makedirs(self.mask_dir) # saveImg = self.maskQimage.convertToFormat(QImage.Format_Grayscale8) # This was bugging out and making the image not the same size as it started # saveImg = self.maskQimage.convertToFormat(QImage.Format_Grayscale8).scaled(self.originalWidth,self.originalHeight,aspectRatioMode=Qt.KeepAspectRatio) saveImg = self.maskQimage.convertToFormat( QImage.Format_Grayscale8).scaled(self.originalWidth, self.originalHeight) qimgHeight = saveImg.height() qimgWidth = saveImg.width() print(self.originalHeight, self.originalWidth, qimgHeight, qimgWidth) saveArr = np.zeros((qimgHeight, qimgWidth), dtype='uint8') for rowIndex in range(qimgHeight): for colIndex in range(qimgWidth): pixVal = qGray(saveImg.pixel(colIndex, rowIndex)) if pixVal > 0: saveArr[rowIndex, colIndex] = 1 io.imsave(savePath, saveArr)
def shift(bitmap, direction): new_bmp = QImage( bitmap ) new_bmp.fill(0) if direction not in [ 'left', 'right', 'up', 'down' ]: error('direction for shift char not valid, exit.' ) for y in range( bitmap.height() ): for x in range( bitmap.width() ): if qGray( bitmap.pixel( x, y ) ): col = 1 else: col = 0 if direction == 'left' and x > 0: new_bmp.setPixel( x - 1, y, col) elif direction == 'right' and x < bitmap.width() - 1: new_bmp.setPixel( x + 1, y, col ) elif direction == 'up' and y > 0: new_bmp.setPixel( x, y - 1, col) elif direction == 'down' and y < bitmap.height() - 1: new_bmp.setPixel( x, y + 1, col ) return new_bmp
def shift(bitmap, direction): new_bmp = QImage(bitmap) new_bmp.fill(0) if direction not in ['left', 'right', 'up', 'down']: error('direction for shift char not valid, exit.') for y in range(bitmap.height()): for x in range(bitmap.width()): if qGray(bitmap.pixel(x, y)): col = 1 else: col = 0 if direction == 'left' and x > 0: new_bmp.setPixel(x - 1, y, col) elif direction == 'right' and x < bitmap.width() - 1: new_bmp.setPixel(x + 1, y, col) elif direction == 'up' and y > 0: new_bmp.setPixel(x, y - 1, col) elif direction == 'down' and y < bitmap.height() - 1: new_bmp.setPixel(x, y + 1, col) return new_bmp
def find_darkest_neighbor(self, image, cx, cy): darkest_neighbor = 256 half_radius = self.parent.reductionNeighborhoodWalkify.value() min_x = Mapping.clip_value(cx - half_radius, half_radius, image.width() - half_radius) min_y = Mapping.clip_value(cy - half_radius, half_radius, image.height() - half_radius) max_x = Mapping.clip_value(cx + half_radius, half_radius, image.width() - half_radius) max_y = Mapping.clip_value(cy + half_radius, half_radius, image.height() - half_radius) for x in range(min_x, max_x + 1): for y in range(min_y, max_y + 1): distance = sqrt((x - cx)**2 + (y - cy)**2) if distance < half_radius: currcolor = qGray(image.pixel(x, y)) + random() * 0.01 if currcolor < darkest_neighbor: darkest_x = x darkest_y = y darkest_neighbor = currcolor return darkest_x, darkest_y, darkest_neighbor
def desaturate(image): p = 100.0 / image.height() msg = tr('Desaturate the Image. Press ESC to Cancel.') pixel = image.pixel event.CANCEL = False if not image.isGrayscale(): tem_image = QImage(image.width(), image.height(), QImage.Format_Indexed8) tem_image.setColorTable(GRAYSCALE_COLORTABLE) width = range(image.width()) for imy in range(image.height()): for imx in width: lightness = qGray(pixel(imx, imy)) tem_image.setPixel(imx, imy, lightness) event.emit(event.APP_STATUS, text=msg, progress=p * imy) if event.CANCEL: break if not event.CANCEL: image = tem_image event.emit(event.APP_STATUS) return image
def processFrame(self, frame, levels): histogram = [0.0] * levels if levels and frame.map(QAbstractVideoBuffer.ReadOnly): pixelFormat = frame.pixelFormat() if pixelFormat == QVideoFrame.Format_YUV420P or pixelFormat == QVideoFrame.Format_NV12: # Process YUV data. bits = frame.bits() for idx in range(frame.height() * frame.width()): histogram[(bits[idx] * levels) >> 8] += 1.0 else: imageFormat = QVideoFrame.imageFormatFromPixelFormat(pixelFormat) if imageFormat != QImage.Format_Invalid: # Process RGB data. image = QImage(frame.bits(), frame.width(), frame.height(), imageFormat) for y in range(image.height()): for x in range(image.width()): pixel = image.pixel(x, y) histogram[(qGray(pixel) * levels) >> 8] += 1.0 # Find the maximum value. maxValue = 0.0 for value in histogram: if value > maxValue: maxValue = value # Normalise the values between 0 and 1. if maxValue > 0.0: for i in range(len(histogram)): histogram[i] /= maxValue frame.unmap() self.histogramReady.emit(histogram)
def makeBubbles(self, image): """ helper method for bubblification (contains the actual calculations) :param image: :return: """ self.parent.progressBarBubblify.setVisible(True) self.parent.application.processEvents() minBrightness = self.parent.minBrightnessBubblify.value() maxBrightness = self.parent.maxBrightnessBubblify.value() minCircleRadius = self.parent.minRadiusBubblify.value() maxCircleRadius = self.parent.maxRadiusBubblify.value() invertColors = self.parent.invertColorsBubblify.checkState( ) == Qt.Checked minProbability = self.parent.minProbabilityBubblify.value() maxProbablity = self.parent.maxProbabilityBubblify.value() radiustolerance = self.parent.radiusToleranceBubblify.value() strokeWidth = 1 # remove existing data on this layer self.removeOldGraphicsItems() # first add seeding points print("Seeding points") spots = [] circles = [] for x in range(image.width()): for y in range(image.height()): grayvalue = qGray(image.pixel(x, y)) if invertColors: grayvalue = 255 - grayvalue if minBrightness < grayvalue < maxBrightness: probability = Mapping.linexp(grayvalue, 0, 255, maxProbablity / 100, minProbability / 100) addNow = random() < probability if addNow: spots.append([x, y]) print("Optimizing {0} points".format(len(spots))) # next find out radii we can use that avoid overlap print("Analyzing radii") if len(spots): tree = spatial.KDTree(spots) for center in spots: x = center[0] y = center[1] grayvalue = qGray(image.pixel(x, y)) proposed_radius = Mapping.linexp(grayvalue, minBrightness, maxBrightness, minCircleRadius, maxCircleRadius) nearest_neighbor = tree.query(np.array([[x, y]]), 2) # print("{0} nearest to {1}".format(nearest_neighbor, [x,y])) if nearest_neighbor: try: distance = nearest_neighbor[0][0][1] maxradius = np.floor(distance / 2) minimum = min(proposed_radius, maxradius) # print("Using minimum of proposed {0} and max {1}".format(proposed_radius, maxradius)) if minimum >= proposed_radius * radiustolerance: circles.append((x, y, minimum)) except: print("weird nearest neighbor: ", nearest_neighbor) print("Visualize") # next, visualize group = QGraphicsItemGroup() for c in circles: x = c[0] y = c[1] r = c[2] item = QGraphicsEllipseItem(x - r, y - r, r * 2, r * 2) pen = QPen() pen.setWidth(strokeWidth) item.setPen(pen) group.addToGroup(item) self.addNewGraphicsItems(group) self.parent.progressBarBubblify.setVisible(False)
def data(self, index, role): if not index.isValid() or role != Qt.DisplayRole: return None return qGray(self.modelImage.pixel(index.column(), index.row()))
def draw_icon(icon, rect, painter, icon_mode, shadow=False): cache = icon.pixmap(rect.size()) dip_offset = QPoint(1, -2) cache = QPixmap() pixname = "icon {0} {1} {2}".format(icon.cacheKey(), icon_mode, rect.height()) if QPixmapCache.find(pixname) is None: pix = icon.pixmap(rect.size()) device_pixel_ratio = pix.devicePixelRatio() radius = 3 * device_pixel_ratio offset = dip_offset * device_pixel_ratio cache = QPixmap(pix.size() + QSize(radius * 2, radius * 2)) cache.fill(Qt.transparent) cache_painter = QPainter(cache) if icon_mode == QIcon.Disabled: im = pix.toImage().convertToFormat(QImage.Format_ARGB32) for y in range(0, im.height()): scanline = im.scanLine(y) for x in range(0, im.width()): pixel = scanline intensity = qGray(pixel) scanline = qRgba(intensity, intensity, intensity, qAlpha(pixel)) scanline += 1 pix = QPixmap.fromImage(im) # Draw shadow tmp = QImage(pix.size() + QSize(radius * 2, radius * 2), QImage.Format_ARGB32_Premultiplied) tmp.fill(Qt.transparent) tmp_painter = QPainter(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_Source) tmp_painter.drawPixmap( QRect(radius, radius, pix.width(), pix.height()), pix) tmp_painter.end() # Blur the alpha channel blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied) blur_painter = QPainter(blurred) blur_painter.end() # tmp = blurred tmp_painter.begin(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150)) tmp_painter.end() tmp_painter.begin(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150)) tmp_painter.end() # Draw the blurred drop shadow cache_painter.drawImage( QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp) # Draw the actual pixmap cache_painter.drawPixmap( QRect( QPoint(radius, radius) + offset, QSize(pix.width(), pix.height())), pix) cache_painter.end() cache.setDevicePixelRatio(device_pixel_ratio) QPixmapCache.insert(pixname, cache) target_rect = cache.rect() target_rect.setSize(target_rect.size() / cache.devicePixelRatio()) target_rect.moveCenter(rect.center() - dip_offset) painter.drawPixmap(target_rect, cache)
def draw_icon(icon, rect, painter, icon_mode, shadow=False): cache = icon.pixmap(rect.size()) dip_offset = QPoint(1, -2) cache = QPixmap() pixname = "icon {0} {1} {2}".format( icon.cacheKey(), icon_mode, rect.height() ) if QPixmapCache.find(pixname) is None: pix = icon.pixmap(rect.size()) device_pixel_ratio = pix.devicePixelRatio() radius = 3 * device_pixel_ratio offset = dip_offset * device_pixel_ratio cache = QPixmap(pix.size() + QSize(radius * 2, radius * 2)) cache.fill(Qt.transparent) cache_painter = QPainter(cache) if icon_mode == QIcon.Disabled: im = pix.toImage().convertToFormat(QImage.Format_ARGB32) for y in range(0, im.height()): scanline = im.scanLine(y) for x in range(0, im.width()): pixel = scanline intensity = qGray(pixel) scanline = qRgba( intensity, intensity, intensity, qAlpha(pixel)) scanline += 1 pix = QPixmap.fromImage(im) # Draw shadow tmp = QImage(pix.size() + QSize(radius * 2, radius * 2), QImage.Format_ARGB32_Premultiplied) tmp.fill(Qt.transparent) tmp_painter = QPainter(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_Source) tmp_painter.drawPixmap( QRect(radius, radius, pix.width(), pix.height()), pix) tmp_painter.end() # Blur the alpha channel blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied) blur_painter = QPainter(blurred) blur_painter.end() # tmp = blurred tmp_painter.begin(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150)) tmp_painter.end() tmp_painter.begin(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150)) tmp_painter.end() # Draw the blurred drop shadow cache_painter.drawImage( QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp) # Draw the actual pixmap cache_painter.drawPixmap( QRect(QPoint(radius, radius) + offset, QSize(pix.width(), pix.height())), pix) cache_painter.end() cache.setDevicePixelRatio(device_pixel_ratio) QPixmapCache.insert(pixname, cache) target_rect = cache.rect() target_rect.setSize(target_rect.size() / cache.devicePixelRatio()) target_rect.moveCenter(rect.center() - dip_offset) painter.drawPixmap(target_rect, cache)
def getGrayPixel(image): w, h = (image.width(), image.height()) pixels = [qGray(image.pixel(x, y)) for x, y in zip(xrange(w), xrange(h))] return pixels
def setThemeEditorDatas(editor, themeDatas, pixmap, screenRect): textRect = themeTextRect(themeDatas, screenRect) x, y, width, height = themeEditorGeometry(themeDatas, textRect) editor.setGeometry(x, y, width, height) # p = editor.palette() ##p.setBrush(QPalette.Base, QBrush(pixmap.copy(x, y, width, height))) # p.setBrush(QPalette.Base, QColor(Qt.transparent)) # p.setColor(QPalette.Text, QColor(themeDatas["Text/Color"])) # p.setColor(QPalette.Highlight, QColor(themeDatas["Text/Color"])) # p.setColor(QPalette.HighlightedText, Qt.black if qGray(QColor(themeDatas["Text/Color"]).rgb()) > 127 else Qt.white) # editor.setPalette(p) editor.setAttribute(Qt.WA_NoSystemBackground, True) bf = getThemeBlockFormat(themeDatas) editor.setDefaultBlockFormat(bf) # b = editor.document().firstBlock() # cursor = editor.textCursor() # cursor.setBlockFormat(bf) # while b.isValid(): # bf2 = b.blockFormat() # bf2.merge(bf) # cursor.setPosition(b.position()) ##cursor.setPosition(b.position(), QTextCursor.KeepAnchor) # cursor.setBlockFormat(bf2) # b = b.next() editor.setTabStopWidth(themeDatas["Spacings/TabWidth"]) editor.document().setIndentWidth(themeDatas["Spacings/TabWidth"]) editor.highlighter.setMisspelledColor(QColor(themeDatas["Text/Misspelled"])) cf = QTextCharFormat() # f = QFont() # f.fromString(themeDatas["Text/Font"]) # cf.setFont(f) editor.highlighter.setDefaultCharFormat(cf) f = QFont() f.fromString(themeDatas["Text/Font"]) # editor.setFont(f) editor.setStyleSheet(""" background: transparent; color: {foreground}; font-family: {ff}; font-size: {fs}; selection-color: {sc}; selection-background-color: {sbc}; """.format( foreground=themeDatas["Text/Color"], ff=f.family(), fs="{}pt".format(str(f.pointSize())), sc="black" if qGray(QColor(themeDatas["Text/Color"]).rgb()) > 127 else "white", sbc=themeDatas["Text/Color"], ) ) editor._fromTheme = True editor._themeData = themeDatas editor.highlighter.updateColorScheme()