def create_mask(self, control_image, rendered_image, mask_image, overload=1): max_width = min(rendered_image.width(), control_image.width()) max_height = min(rendered_image.height(), control_image.height()) new_mask_image = QImage(control_image.width(), control_image.height(), QImage.Format_ARGB32) new_mask_image.fill(QColor(0, 0, 0)) # loop through pixels in rendered image and compare mismatch_count = 0 linebytes = max_width * 4 for y in range(max_height): control_scanline = control_image.constScanLine(y).asstring(linebytes) rendered_scanline = rendered_image.constScanLine(y).asstring(linebytes) mask_scanline = mask_image.scanLine(y).asstring(linebytes) for x in range(max_width): currentTolerance = qRed(struct.unpack("I", mask_scanline[x * 4 : x * 4 + 4])[0]) if currentTolerance == 255: # ignore pixel new_mask_image.setPixel(x, y, qRgb(currentTolerance, currentTolerance, currentTolerance)) continue expected_rgb = struct.unpack("I", control_scanline[x * 4 : x * 4 + 4])[0] rendered_rgb = struct.unpack("I", rendered_scanline[x * 4 : x * 4 + 4])[0] difference = min(255, colorDiff(expected_rgb, rendered_rgb) * overload) if difference > currentTolerance: # update mask image new_mask_image.setPixel(x, y, qRgb(difference, difference, difference)) mismatch_count += 1 else: new_mask_image.setPixel(x, y, qRgb(currentTolerance, currentTolerance, currentTolerance)) return new_mask_image
def rgbFromWaveLength(self, wave): r = 0.0 g = 0.0 b = 0.0 if wave >= 380.0 and wave <= 440.0: r = -1.0 * (wave - 440.0) / (440.0 - 380.0) b = 1.0 elif wave >= 440.0 and wave <= 490.0: g = (wave - 440.0) / (490.0 - 440.0) b = 1.0 elif wave >= 490.0 and wave <= 510.0: g = 1.0 b = -1.0 * (wave - 510.0) / (510.0 - 490.0) elif wave >= 510.0 and wave <= 580.0: r = (wave - 510.0) / (580.0 - 510.0) g = 1.0 elif wave >= 580.0 and wave <= 645.0: r = 1.0 g = -1.0 * (wave - 645.0) / (645.0 - 580.0) elif wave >= 645.0 and wave <= 780.0: r = 1.0 s = 1.0 if wave > 700.0: s = 0.3 + 0.7 * (780.0 - wave) / (780.0 - 700.0) elif wave < 420.0: s = 0.3 + 0.7 * (wave - 380.0) / (420.0 - 380.0) r = pow(r * s, 0.8) g = pow(g * s, 0.8) b = pow(b * s, 0.8) return qRgb(r*255, g*255, b*255)
def test_rgb(self): # from https://doc.qt.io/archives/qt-4.8/qcolor.html # typedef QRgb # An ARGB quadruplet on the format #AARRGGBB, # equivalent to an unsigned int. if ImageQt.qt_version == '5': from PyQt5.QtGui import qRgb elif ImageQt.qt_version == '4': from PyQt4.QtGui import qRgb elif ImageQt.qt_version == 'side': from PySide.QtGui import qRgb elif ImageQt.qt_version == 'side2': from PySide2.QtGui import qRgb self.assertEqual(qRgb(0, 0, 0), qRgba(0, 0, 0, 255)) def checkrgb(r, g, b): val = ImageQt.rgb(r, g, b) val = val % 2**24 # drop the alpha self.assertEqual(val >> 16, r) self.assertEqual(((val >> 8) % 2**8), g) self.assertEqual(val % 2**8, b) checkrgb(0, 0, 0) checkrgb(255, 0, 0) checkrgb(0, 255, 0) checkrgb(0, 0, 255)
def updateMask(control_image_path, rendered_image_path, mask_image_path): control_image = imageFromPath(control_image_path) if not control_image: error("Could not read control image {}".format(control_image_path)) rendered_image = imageFromPath(rendered_image_path) if not rendered_image: error("Could not read rendered image {}".format(rendered_image_path)) if not rendered_image.width() == control_image.width() or not rendered_image.height() == control_image.height(): print( ( "Size mismatch - control image is {}x{}, rendered image is {}x{}".format( control_image.width(), control_image.height(), rendered_image.width(), rendered_image.height() ) ) ) max_width = min(rendered_image.width(), control_image.width()) max_height = min(rendered_image.height(), control_image.height()) # read current mask, if it exist mask_image = imageFromPath(mask_image_path) if mask_image.isNull(): print("Mask image does not exist, creating {}".format(mask_image_path)) mask_image = QImage(control_image.width(), control_image.height(), QImage.Format_ARGB32) mask_image.fill(QColor(0, 0, 0)) # loop through pixels in rendered image and compare mismatch_count = 0 linebytes = max_width * 4 for y in range(max_height): control_scanline = control_image.constScanLine(y).asstring(linebytes) rendered_scanline = rendered_image.constScanLine(y).asstring(linebytes) mask_scanline = mask_image.scanLine(y).asstring(linebytes) for x in range(max_width): currentTolerance = qRed(struct.unpack("I", mask_scanline[x * 4 : x * 4 + 4])[0]) if currentTolerance == 255: # ignore pixel continue expected_rgb = struct.unpack("I", control_scanline[x * 4 : x * 4 + 4])[0] rendered_rgb = struct.unpack("I", rendered_scanline[x * 4 : x * 4 + 4])[0] difference = colorDiff(expected_rgb, rendered_rgb) if difference > currentTolerance: # update mask image mask_image.setPixel(x, y, qRgb(difference, difference, difference)) mismatch_count += 1 if mismatch_count: # update mask mask_image.save(mask_image_path, "png") print("Updated {} pixels in {}".format(mismatch_count, mask_image_path)) else: print("No mismatches in {}".format(mask_image_path))
def resizeImage(self, image, newSize): if image.size() == newSize: return newImage = QImage(newSize, QImage.Format_RGB32) newImage.fill(qRgb(255, 255, 255)) painter = QPainter(newImage) painter.drawImage(QPoint(0, 0), image) self.image = newImage
def __init__(self, vncclient=None, parent=None): super(VNCViewer, self).__init__(parent) self.setMouseTracking(True) self.setFocusPolicy(Qt.WheelFocus) # self.setCursor(Qt.BlankCursor) self.client = vncclient or parent.client self.client.started.connect(self._SH_ClientStarted) self.client.finished.connect(self._SH_ClientFinished) self.client.imageSizeChanged.connect(self._SH_ImageSizeChanged) self.client.imageChanged.connect(self._SH_ImageUpdated) self.client.passwordRequested.connect(self._SH_PasswordRequested, Qt.BlockingQueuedConnection) self.colors_8bit = [qRgb((i & 0x07) << 5, (i & 0x38) << 2, i & 0xc0) for i in range(256)] self.scale = False self.view_only = False self._client_active = False self._has_mouse_over = False self._active_keys = ActiveKeys()
def test_rgb(): # from https://qt-project.org/doc/qt-4.8/qcolor.html # typedef QRgb # An ARGB quadruplet on the format #AARRGGBB, equivalent to an unsigned int. assert_equal(qRgb(0,0,0), qRgba(0,0,0,255)) def checkrgb(r,g,b): val = ImageQt.rgb(r,g,b) val = val % 2**24 # drop the alpha assert_equal(val >> 16, r) assert_equal(((val >> 8 ) % 2**8), g) assert_equal(val % 2**8, b) checkrgb(0,0,0) checkrgb(255,0,0) checkrgb(0,255,0) checkrgb(0,0,255)
def toQImage(frame, copy=False): gray_color_table = [qRgb(i, i, i) for i in range(256)] if frame is None: return QImage() im = np.asarray(frame) if im.dtype == np.uint8: if len(im.shape) == 2: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8) qim.setColorTable(gray_color_table) return qim.copy() if copy else qim elif len(im.shape) == 3: if im.shape[2] == 3: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888) return qim.copy() if copy else qim elif im.shape[2] == 4: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32) return qim.copy() if copy else qim
def create_diff_image(self, control_image, rendered_image, mask_image): # loop through pixels in rendered image and compare mismatch_count = 0 max_width = min(rendered_image.width(), control_image.width()) max_height = min(rendered_image.height(), control_image.height()) linebytes = max_width * 4 diff_image = QImage( control_image.width(), control_image.height(), QImage.Format_ARGB32) diff_image.fill(QColor(152, 219, 249)) for y in range(max_height): control_scanline = control_image.constScanLine( y).asstring(linebytes) rendered_scanline = rendered_image.constScanLine( y).asstring(linebytes) mask_scanline = mask_image.scanLine(y).asstring(linebytes) for x in range(max_width): currentTolerance = qRed( struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0]) if currentTolerance == 255: # ignore pixel continue expected_rgb = struct.unpack( 'I', control_scanline[x * 4:x * 4 + 4])[0] rendered_rgb = struct.unpack( 'I', rendered_scanline[x * 4:x * 4 + 4])[0] difference = colorDiff(expected_rgb, rendered_rgb) if difference > currentTolerance: # update mask image diff_image.setPixel(x, y, qRgb(255, 0, 0)) mismatch_count += 1 if mismatch_count: return diff_image else: print('No mismatches') return None
def array_to_qimage(im: np.ndarray, copy=False): gray_color_table = [qRgb(i, i, i) for i in range(256)] if im is None: return QImage() if im.dtype == np.uint8: if len(im.shape) == 2: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8) qim.setColorTable(gray_color_table) return qim.copy() if copy else qim elif len(im.shape) == 3: if im.shape[2] == 3: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888) return qim.copy() if copy else qim elif im.shape[2] == 4: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32) return qim.copy() if copy else qim
def toQImage(im, copy=False): if im is None: return QImage() if im.dtype == numpy.uint8: if len(im.shape) == 2: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8) qim.setColorTable([qRgb(i, i, i) for i in range(256)]) return qim.copy() if copy else qim elif len(im.shape) == 3: if im.shape[2] == 3: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888) return qim.copy() if copy else qim elif im.shape[2] == 4: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32) return qim.copy() if copy else qim
def render_img(self, buffers, addr, mouse_offs): colors = [] goffs = 0 for mapped, buf in buffers: xrefs = [] if mapped: for i in xrange(len(buf)): xrefs.append(self.xrefcount(addr + goffs + i)) if xrefs: minimum, maximum = min(xrefs), max(xrefs) for count in xrefs: r, g, b = self.hm(minimum, maximum, count) colors.append((True, qRgb(r, g, b))) else: for i in xrange(len(buf)): colors.append((False, 0)) goffs += len(buf) return colors
def render_img(self, buffers, addr, mouse_offs): colors = [] for mapped, buf in buffers: offs = 0 matches = [] if mapped: if self.regex is not None: for m in re.finditer(self.regex, buf): matches += range(m.start(), m.end()) for c in buf: r = g = b = ord(c) & 0x3F if offs in matches: r, g, b = (r + (0xFF - 0x3F) & 0xFF, g, b) colors.append((True, qRgb(r, g, b))) offs += 1 else: for i in xrange(len(buf)): colors.append((False, 0)) return colors
def addROItoImage(self, roi): logger.info("GraphicsItem.addROItoImage called") listROICoords = self.getListRoiInnerPoints(roi) if listROICoords is not None: for coords in listROICoords: #x = coords[0] #y = coords[1] x = coords[1] y = coords[0] #print("({}, {})".format(x, y)) pixelColour = self.qimage.pixel(x, y) pixelRGB = QColor(pixelColour).getRgb() redVal = pixelRGB[0] greenVal = pixelRGB[1] blueVal = pixelRGB[2] if greenVal == 255 and blueVal == 255: #This pixel would be white if red channel set to 255 #so set the green and blue channels to zero greenVal = blueVal = 0 value = qRgb(255, greenVal, blueVal) self.qimage.setPixel(x, y, value)
def fillFreeHandRoi(self, listCoords): for coords in listCoords: #x = coords[0] #y = coords[1] x = coords[1] y = coords[0] pixelColour = self.qimage.pixel(x, y) pixelRGB = QtGui.QColor(pixelColour).getRgb() redVal = pixelRGB[0] greenVal = pixelRGB[1] blueVal = pixelRGB[2] if greenVal == 255 and blueVal == 255: #This pixel would be white if red channel set to 255 #so set the green and blue channels to zero greenVal = blueVal = 0 value = qRgb(255, greenVal, blueVal) self.qimage.setPixel(x, y, value) #convert QImage to QPixmap to be able to update image #with filled ROI self.pixMap = QPixmap.fromImage(self.qimage) self.update()
def __init__(self, vncclient=None, parent=None): super(VNCViewer, self).__init__(parent) self.setMouseTracking(True) self.setFocusPolicy(Qt.WheelFocus) # self.setCursor(Qt.BlankCursor) self.client = vncclient or parent.client self.client.started.connect(self._SH_ClientStarted) self.client.finished.connect(self._SH_ClientFinished) self.client.imageSizeChanged.connect(self._SH_ImageSizeChanged) self.client.imageChanged.connect(self._SH_ImageUpdated) self.client.passwordRequested.connect(self._SH_PasswordRequested, Qt.BlockingQueuedConnection) self.colors_8bit = [ qRgb((i & 0x07) << 5, (i & 0x38) << 2, i & 0xc0) for i in range(256) ] self.scale = False self.view_only = False self._client_active = False self._has_mouse_over = False self._active_keys = ActiveKeys()
def __init__(self): super().__init__() sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.setSizePolicy(sizePolicy) self.setFocusPolicy(Qt.StrongFocus) self.lastPoint = QPoint() # 判断鼠标触摸点在SketchArea内 self.scribbling = False # 画笔 self.penWidth = 3 self.penColor = Qt.black #self.pen = QPen(Qt.black, self.penWidth, Qt.SolidLine) self.image = QImage(500, 500, QImage.Format_RGB32) self.image.fill(qRgb(255, 255, 255)) self.sketch = [] self.stroke = [] self.initUi()
def on_process_buffer(self, buffers, addr, size, mouse_offs): colors = [] goffs = 0 for mapped, buf in buffers: if mapped: for offs in range(len(buf)): r = g = b = 0 c = buf[offs] & 0xFF ea = addr + goffs + offs f = get_func(ea) if f: g = b = c elif self._is_string(ea): g = c else: r = g = b = c colors.append((True, qRgb(r, g, b))) else: colors += [(False, None)]*len(buf) goffs += len(buf) return colors
def convertToSepia(self): """Convert image to sepia filter.""" #TODO: Sepia #704214 rgb(112, 66, 20) #TODO: optimize speed that the image converts, or add to thread if self.image.isNull() == False: for row_pixel in range(self.image.width()): for col_pixel in range(self.image.height()): current_val = QColor(self.image.pixel( row_pixel, col_pixel)) # Calculate r, g, b values for current pixel red = current_val.red() green = current_val.green() blue = current_val.blue() new_red = int(0.393 * red + 0.769 * green + 0.189 * blue) new_green = int(0.349 * red + 0.686 * green + 0.168 * blue) new_blue = int(0.272 * red + 0.534 * green + 0.131 * blue) # Set the new RGB values for the current pixel if new_red > 255: red = 255 else: red = new_red if new_green > 255: green = 255 else: green = new_green if new_blue > 255: blue = 255 else: blue = new_blue new_value = qRgb(red, green, blue) self.image.setPixel(row_pixel, col_pixel, new_value) self.setPixmap(QPixmap().fromImage(self.image)) self.repaint()
def changeContrast(self, contrast): """Change the contrast of the pixels in the image. Contrast is the difference between max and min pixel intensity.""" for row_pixel in range(self.image.width()): for col_pixel in range(self.image.height()): # Calculate a contrast correction factor factor = float(259 * (contrast + 255) / (255 * (259 - contrast))) current_val = QColor(self.image.pixel(row_pixel, col_pixel)) red = current_val.red() green = current_val.green() blue = current_val.blue() new_red = factor * (red - 128) + 128 new_green = factor * (green - 128) + 128 new_blue = factor * (blue - 128) + 128 new_value = qRgb(new_red, new_green, new_blue) self.image.setPixel(row_pixel, col_pixel, new_value) self.setPixmap(QPixmap().fromImage(self.image))
def setColorMap(self, colormap=None, limits=None): if colormap is None: colormap = [[0, 0, 0], [255, 255, 255]] if limits is None: limits = [0.0, 1.0] nColors = len(colormap) step = float(limits[1] - limits[0])/(self.nLabels - 1) labelValues = [i*step for i in range(self.nLabels)] maxVal = abs(max(labelValues)) if maxVal > 0.1: self.labels = ['%.2f' % value for value in labelValues] else: self.labels = ['%.2E' % value for value in labelValues] self.labelPos = [float(i)/(self.nLabels - 1) for i in range(self.nLabels)] fm = self.fontMetrics() flag = QtCore.Qt.TextSingleLine sizes = [fm.size(flag, label) for label in self.labels] self.labelOffset = [0.3 * size.height() for size in sizes] self.labelOffset[0] /= 0.3 self.labelOffset[len(self.labelOffset) - 1] = 0 self.labelMaxWidth = max([size.width() for size in sizes]) self.qImage = QImage(1, nColors, QImage.Format_RGB32) for i in range(nColors): color = colormap[i] self.qImage.setPixel(0, i, qRgb(color[0], color[1], color[2])) margin = max(self.labelOffset) self.setContentsMargins(margin, margin, margin, margin) self.widthHint = self.barWidth + self.labelMaxWidth + self.labelMargin + 2*margin + 1 self.updateGeometry() self.update()
def on_process_buffer(self, buffers, addr, size, mouse_offs): colors = [] goffs = 0 for mapped, buf in buffers: if mapped: ip = get_ip_val() i = 0 while i < len(buf): if ip is not None and ip == addr + goffs + i and self.hook.highlighted: size = get_item_size(ip) for j in xrange(size): colors.append((True, qRgb(0xFF, 0x45, 0))) i += size continue else: if addr + goffs + i in self.hook.hits: data = self.hook.hits[addr + goffs + i] size = data[1] hits = data[0] for j in xrange(size): base = self.palette[len(self.palette) - 1] col = QColor(base).darker( 100 + (float(hits) / self.hook.maxhits) * 105).rgb() colors.append((True, col)) i += size continue else: c = ord(buf[i]) colors.append( (True, self.palette[self._byte2coloridx(c)])) i += 1 else: for i in xrange(len(buf)): colors.append((False, None)) goffs += len(buf) return colors
def test_rgb(): # from https://doc.qt.io/archives/qt-4.8/qcolor.html # typedef QRgb # An ARGB quadruplet on the format #AARRGGBB, # equivalent to an unsigned int. if ImageQt.qt_version == "5": from PyQt5.QtGui import qRgb elif ImageQt.qt_version == "side2": from PySide2.QtGui import qRgb assert qRgb(0, 0, 0) == qRgba(0, 0, 0, 255) def checkrgb(r, g, b): val = ImageQt.rgb(r, g, b) val = val % 2**24 # drop the alpha assert val >> 16 == r assert ((val >> 8) % 2**8) == g assert val % 2**8 == b checkrgb(0, 0, 0) checkrgb(255, 0, 0) checkrgb(0, 255, 0) checkrgb(0, 0, 255)
def get_transformed_pixel(self): try: self.actual_pixel_list = self.actual_pixel_list.reshape( self.linhas, self.colunas) except ValueError as error: index = int(len(self.actual_pixel_list) / 2) result = self.actual_pixel_list[index].rgb() self.actual_pixel_list = np.array([]) return result red_sum, green_sum, blue_sum = 0, 0, 0 for x in range(0, len(self.actual_pixel_list)): for y in range(0, len(self.actual_pixel_list[0])): red_sum += self.actual_pixel_list[x][y].red( ) * self.mask.matrix[x][y] green_sum += self.actual_pixel_list[x][y].green( ) * self.mask.matrix[x][y] blue_sum += self.actual_pixel_list[x][y].blue( ) * self.mask.matrix[x][y] red_sum, green_sum, blue_sum = ColorHelper.limit_color( [red_sum, green_sum, blue_sum]) result = qRgb(red_sum, green_sum, blue_sum) self.actual_pixel_list = np.array([]) return result
def toQImage(self, im): gray_color_table = [qRgb(0, i, 0) for i in range(256)] if im is None: return QImage() im_255 = im * 255 #float64 define el rango de [0-255] de grayscale como [0-1] con decimales, hay que multiplicar por 255. img_8 = im_255.astype(np.uint8) #entonces la convertimos a int8 if img_8.dtype == np.uint8: img_8 = np.require(img_8, np.uint8, 'C') if len( img_8.shape ) == 2: #dependiendo del número de canales que tenga, significará que la imagen es en grayscale, RGB o ARGB self.qim = QImage( img_8.data, img_8.shape[1], img_8.shape[0], img_8.strides[0], QImage.Format_Indexed8) #transformamos a QImage self.qim.setColorTable(gray_color_table) elif len( img_8.shape ) == 3: #si el shape de la I es 3, es porque tenemos (x_pix, y_pix, canales) if img_8.shape[2] == 3: #ahora podemos tener 3 canales (RGB) self.qim = QImage(img_8.data, img_8.shape[1], img_8.shape[0], img_8.strides[0], QImage.Format_RGB888) elif img_8.shape[2] == 4: #o tener 4 canales (ARGB) self.qim = QImage(img_8.data, img_8.shape[1], img_8.shape[0], img_8.strides[0], QImage.Format_ARGB32) self.imageLabel_2.setPhoto(QtGui.QPixmap( self.qim)) #qim es la imagen ya en qImage
def __init__(self, radious=20, parent=None): super(ImageWidget, self).__init__(parent) assert (radious >= 0) self.scaling_factor = 1.5 self.image = None self.contour_set = [] self.current_image = None self.circle_radious = radious self.circle_center = None self.manual_polygon = QPolygonF() self.last_contour = [] self.initial_contours = None self.view_mode = NORMAL_IMAGE self.contours_colors = [ Qt.yellow, Qt.cyan, Qt.blue, Qt.red, Qt.green, Qt.white, Qt.black, Qt.darkRed, Qt.darkGreen, Qt.magenta, Qt.darkYellow, Qt.gray, ] # We create a grayscale colortable for showing the grayscale value in the image. # This indexed image implementation is inspired on # https://forum.qt.io/topic/102688/numpy-grayscale-array-2d-to-rgb-qimage-or-qpixmap-in-either-red-green-or-blue/2 self.grayscale_colortable = np.array( [qRgb(i, i, i) for i in range(256)]) self.image_mode(self.view_mode)
def _toQImage(arr, do_copy=False): """Convert NumPy ndarray to QImage format. Taken from: https://gist.github.com/smex/5287589 Args: arr: NumPy array to convert. do_copy: If true, copy the QImage file before returning. Returns: QImage formatted image. """ if arr is None: return QImage() gray_color_table = [qRgb(i, i, i) for i in range(256)] if arr.dtype == np.uint8: if len(arr.shape) == 2: qim = QImage(arr.data, arr.shape[1], arr.shape[0], arr.strides[0], QImage.Format_Indexed8) qim.setColorTable(gray_color_table) return qim.copy() if do_copy else qim elif len(arr.shape) == 3: if arr.shape[2] == 3: qim = QImage(arr.data, arr.shape[1], arr.shape[0], arr.strides[0], QImage.Format_RGB888) return qim.copy() if do_copy else qim elif arr.shape[2] == 4: qim = QImage(arr.data, arr.shape[1], arr.shape[0], arr.strides[0], QImage.Format_ARGB32) return qim.copy() if do_copy else qim raise NotImplementedError('Unsupported image format.')
def __init__(self): super().__init__() self.app = QApplication(sys.argv) self.gray_color_table = [qRgb(i, i, i) for i in range(256)] # self.int_validator = QRegExpValidator(QRegExp("^([+-]?[0-9]\d*|0)$")) self.uint_validator = QRegExpValidator(QRegExp("^([+]?[0-9]\d*|0)$")) self.glevel_validator = QRegExpValidator(QRegExp("\\b(1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\\b")) self.ratio_validator = QRegExpValidator(QRegExp("0+([.][0-9]+)?|1([.]0)?")) self.float_validator = QRegExpValidator(QRegExp("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)")) self.ui = UI(title="Style Transfer") self.ui.transfer_btn.clicked.connect(self.transfer) self.ui.original_browse_btn.clicked.connect(self.set_original_image) self.ui.stlye_browse_btn.clicked.connect(self.set_style_image) self.ui.export_btn.clicked.connect(self.export) self.ui.get_mask_btn.clicked.connect(self.get_segmentation_mask) self.ui.segmentation_mode_combo.currentTextChanged.connect(self.set_stack_view) self.ui.grab_cut_mode_combo.currentTextChanged.connect(self.set_grab_cut_mode) self.ui.cv_init_level_set_combo.currentTextChanged.connect(self.set_chan_vese_init_level) self.ui.mcv_init_level_set_combo.currentTextChanged.connect(self.set_morphological_chan_vese_init_level) self.ui.fs_mcv_mode_combo.currentTextChanged.connect(self.set_fs_morphological_chan_vese_mode) self.set_validators() self.content_image = -1 self.style_image = -1 self.output_image = False self.grab_cut_mode = cv2.GC_INIT_WITH_MASK self.fs_morphological_chan_vese_init_level = "edges" self.chan_vese_init_level = "checkerboard" self.morphological_chan_vese_init_level = "edges" self.x = None self.c = None self.mask = None
def toQImage(self, im): """ Utility method to convert a numpy array to a QImage object. Args: im numpy array to be converted. It can be a 2D (BW) image or a color image (3 channels + alpha) Returns: QImage The image created converting the numpy array """ gray_color_table = [qRgb(i, i, i) for i in range(256)] if im is None: return QImage() if len(im.shape) == 2: # 1 channel image qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8) qim.setColorTable(gray_color_table) return qim elif len(im.shape) == 3: # maybe in the future accept color images (for heatmap) if im.shape[2] == 3: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888) return qim elif im.shape[2] == 4: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32) return qim
def __init__(self): super(MeshViewer, self).__init__() self.gray_color_table = [qRgb(i, i, i) for i in range(256)] self.width = 1024 self.height = 1024 self.imageLabel = QLabel() self.imageLabel.setBackgroundRole(QPalette.Base) self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imageLabel.setScaledContents(True) self.setCentralWidget(self.imageLabel) self.loaded = False self.font = ImageFont.truetype( "/usr/share/fonts/dejavu/DejaVuSans.ttf", 15) self.initMenu() self.meshLoader = MeshLoader() self.setWindowTitle("Mesh Viewer by yj_ju") self.resize(self.width, self.height)
def triangle(coords, win, zbufer,rte,light_dir): new = QColor() #Отрисовка поверхности треугольниками. Внимание тут будет дописан Гуро!!! a = Point(coords[0].x, coords[0].y, coords[0].z, coords[0].norma) b = Point(coords[1].x, coords[1].y, coords[1].z, coords[1].norma) c = Point(coords[2].x, coords[2].y, coords[2].z, coords[2].norma) min_m = min(half_scr_x,half_scr_y) # Преобразование координат к экранным a.x = int(a.x * min_m )+ 150 a.y = 650 - int(a.y * min_m ) a.z = a.z * min_m b.x = int(b.x * min_m ) + 150 b.y = 650 - int(b.y * min_m ) b.z = b.z * min_m c.x = int(c.x * min_m ) +150 c.y = 650 - int(c.y * min_m ) c.z = c.z * min_m #Сортировка по возростанию y a,b,c = sorted([a,b,c], key=lambda p: p.y) I1 = ligh * light_dir.mul(a.norma) I2 = ligh * light_dir.mul(b.norma) I3 = ligh * light_dir.mul(c.norma) # Вырожденный треугольник if a.y == b.y and a.y == c.y: return rte win.pen.setColor(new) total_height = c.y - a.y win.pen.setColor(new) # Цикл по всем строкам треугольника. Каждую строку закрашиваем. for i in range(total_height): # Сначала вычисляем границы строки test = (i > b.y - a.y) or(b.y == a.y) if test: seg = c.y - b.y else: seg = b.y - a.y first = Point(i/total_height, 1, 1,0) if test: second = Point((i - b.y + a.y)/seg, 1, 1,0) else: second = Point(i/seg, 1, 1,0) al = a + (c - a) * first if test: bl = b + (c - b) * second else: bl = a + (b - a) * second #линейная интерполяция if test == False and a.y != b.y: Ia = abs(I1 + ((I2 - I1)/(b.y - a.y))*(i)) elif test and b.y != c.y: Ia = abs(I2 + ((I3 - I2)/(c.y - b.y))*(a.y + i - b.y)) else: Ia = abs(I1 + (I2 - I1) * (i)) if (c.y != a.y): Ib = abs(I1 + ((I3 - I1)/(c.y - a.y))*(i)) else: Ib =abs( I1 + (I3 - I1) * (i)) if al.x > bl.x: al, bl = bl, al else: Ia, Ib = Ib, Ia # Идём от одной вычесленной границы до другой # Пока нет защиты от выхода за границы экрана. for j in range(int(al.x),int(bl.x)+1): if al.x == bl.x: phi = 1 else: phi = (j - al.x)/(bl.x - al.x) p = Point(j,a.y+i,al.z + (bl.z-al.z)*phi,0) idx = int(p.x+p.y*width) # Применяем z-буфер if (bl.x - al.x) == 0: I = abs(Ia + (Ib - Ia)*(p.x-al.x)) else: I = abs(Ia + (Ib - Ia)/(bl.x - al.x)*(p.x - al.x)) #new.setRgb( int(I),int(I),int(I)) try: if (zbufer[idx] < p.z): zbufer[idx] = p.z #win.image.setPixel(p.x, p.y, win.pen.color().rgb()) if p.x < 780 and p.x > 0 and p.y< 650 and p.y > 0: win.image.setPixel(p.x, p.y,qRgb(int(I), int(I), int(I))) except: return rte return rte
import numpy as np import random import colorsys from PyQt5.QtGui import QImage, qRgb from sloth.core.exceptions import NotImplementedException gray_color_table = [qRgb(i, i, i) for i in range(256)] def toQImage(im, copy=False): if im is None: return QImage() if im.dtype == np.uint8: if len(im.shape) == 2: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8) qim.setColorTable(gray_color_table) return qim.copy() if copy else qim elif len(im.shape) == 3: if im.shape[2] == 3: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888) return qim.copy() if copy else qim elif im.shape[2] == 4: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32) return qim.copy() if copy else qim raise NotImplementedException('no conversion to QImage implemented for given image type (depth: %s, shape: %s)' % (im.dtype, im.shape))
class ScreenEGA(QMainWindow): color_palette = [ # CGA color palette: qRgb(0, 0, 0), # black #000000 qRgb(0, 0, 170), # blue #0000aa qRgb(0, 170, 0), # green #00aa00 qRgb(0, 170, 170), # cyan #00aaaa qRgb(170, 0, 0), # red #aa0000 qRgb(170, 0, 170), # magenta #aa00aa qRgb(170, 85, 0), # brown #aa5500 qRgb(170, 170, 170), # light grey #aaaaaa qRgb(85, 85, 85), # dark grey #555555 qRgb(85, 85, 255), # bright blue #5555ff qRgb(85, 255, 85), # bright green #55ff55 qRgb(85, 255, 255), # bright cyan #55ffff qRgb(255, 85, 85), # bright red #ff5555 qRgb(255, 85, 255), # bright magenta #ff55ff qRgb(255, 255, 85), # bright yellow #ffff55 qRgb(255, 255, 255) # bright white #ffffff ] screen_width = 320 screen_height = 200 character_cell_width = 8 character_cell_height = 8 def __init__(self, scale=3): super().__init__() internal_dimension_x = ScreenEGA.screen_width*scale internal_dimension_y = ScreenEGA.screen_height*scale self._screen_scale = scale self._screen_buffer = QImage(internal_dimension_x, internal_dimension_y, QImage.Format_RGB16) self._screen_dbuffer = QImage(internal_dimension_x, internal_dimension_y, QImage.Format_RGB16) self.cls() self.update_screen_buffer() self.resize(internal_dimension_x, internal_dimension_y) self.setWindowTitle('Screen') self._w = QWidget() self._w.resize(internal_dimension_x, internal_dimension_y) self.setCentralWidget(self._w) self._label = QLabel(self) self._label.setGeometry(0, 0, internal_dimension_x, internal_dimension_y) self._pixmap = QPixmap(internal_dimension_x, internal_dimension_y) self._updater = VideoClock() self._updater.updated_screen_buffer.connect(self.update_screen) self._updater.start() def __del__(self): self._updater.stop() @pyqtSlot() def update_screen(self): self._label.setPixmap(QPixmap.fromImage(self._screen_buffer)) self.repaint() def update_screen_buffer(self): self._screen_buffer = self._screen_dbuffer.copy(0, 0, 0, 0) def cls(self): self._screen_dbuffer.fill(ScreenEGA.color_palette[0]) def set_pixel(self, x, y, color_index): """ Set the pixel at the given position to the specified color Maps the virtual 320x200 screen to the actual 640x400 image :param x: x coordinate :param y: y coordinate :param color_index: index of the color in the CGA color palatte """ if x >= 320 or x < 0: raise PixelIndexError() if y >= 200 or y < 0: raise PixelIndexError try: color = ScreenEGA.color_palette[color_index] except: raise PixelColorError() real_x = x*self._screen_scale real_y = y*self._screen_scale for _x in range(0, self._screen_scale): for _y in range(0, self._screen_scale): self._screen_dbuffer.setPixel(QPoint(real_x+_x, real_y+_y), color) def set_character(self, c, x, y, color): LOG.debug("Setting character '{}' at ({}/{}) in color {}".format(c, x, y, color)) if c < 0 or c > 254: raise AsciiIndexError() if x < 0 or x >= ScreenEGA.screen_width/ScreenEGA.character_cell_width: raise CharacterIndexError() if y < 0 or y >= ScreenEGA.screen_height/ScreenEGA.character_cell_height: raise CharacterIndexError() real_x = x*ScreenEGA.character_cell_width real_y = y*ScreenEGA.character_cell_height for xp in range(0, ScreenEGA.character_cell_width): for yp in range(0, ScreenEGA.character_cell_height): if ascii_dos[c][yp][xp]: self.set_pixel(real_x + xp, real_y + yp, color) def draw_relation(self, func, color, start=0, end=319, shift=0): for x in range(start+shift, end+shift+1): ret = func(x) for y in ret: try: self.set_pixel(x, round(y), color) except PixelIndexError: pass def draw_function(self, func, color, start=0, end=319, shift=0, offset=0): for x in range(start+shift, end+shift+1): y = func(x) y_next = func(x+1) try: if y - y_next >= 1 or y - y_next <= -1: self.draw_line((x, y + offset), (x + 1, y_next + offset), color) else: self.set_pixel(x, y + offset, color) except PixelIndexError: pass def draw_square(self, p, width, height, color): self.draw_relation(lambda x: range(p[1], p[1] + height), color, start=p[0], end=p[0] + width) def draw_line(self, a, b, color): # special case: vertical line if a[0] == b[0]: if a[1] < b[1]: x1, y1 = a x2, y2 = b else: x1, y1 = b x2, y2 = a self.draw_relation(lambda x: range(round(y1), round(y2)), color, start=x1, end=x2) return if a[0] < b[0]: x1, y1 = a x2, y2 = b else: x1, y1 = b x2, y2 = a slope = round((y2 - y1) / (x2 - x1), 2) # slope per pixel # self.drawFunction(lambda x: range(y1, y2 + 1), color, start=x1, end=x2) x_current, y_current = x1, y1 for xi in range(x1, x2+1): y_new = y_current + slope if slope <= 1 and slope >= -1: try: self.set_pixel(xi, round(y_new), color) except PixelIndexError: continue else: for yi in range(round(y_current), round(y_current+abs(slope))): try: self.set_pixel(xi, round(yi), color) except PixelIndexError: continue x_current, y_current = xi, y_new def draw_circle(self, p, r, color): for x in range(-r, r): y = round(math.sqrt(abs(math.pow(r, 2)-math.pow(x, 2)))) y_next = round(math.sqrt(abs(math.pow(r, 2)-math.pow(x+1, 2)))) try: if y_next-y >= 1 or y_next-y <= -1: self.draw_line((p[0] + x, p[1] + y - 1), (p[0] + x, p[1] + y_next - 1), color) else: self.set_pixel(p[0] + x, p[1] + y - 1, color) except PixelIndexError: pass try: if y-y_next >= 1 or y-y_next <= -1: self.draw_line((p[0] + x, p[1] - y_next), (p[0] + x, p[1] - y), color) else: self.set_pixel(p[0] + x, p[1] - y, color) except PixelIndexError: pass
Function pix_to_qimage based on Tom Powers code """ import os import sys import ctypes from PyQt5.QtGui import (QImage, qRgb) LIBPATH = "/usr/local/lib64/" LIBPATH_W = r'win32' (L_INSERT, L_COPY, L_CLONE, L_COPY_CLONE) = map(ctypes.c_int, range(4)) # B&W Color Table. _bwCT = [qRgb(255, 255, 255), qRgb(0, 0, 0)] # Grayscale Color Table. _grayscaleCT = [qRgb(i, i, i) for i in range(256)] class BOX(ctypes.Structure): """ Leptonica box structure """ _fields_ = [ ("x", ctypes.c_int32), ("y", ctypes.c_int32), ("w", ctypes.c_int32), ("h", ctypes.c_int32), ("refcount", ctypes.c_uint32) ]
import numpy as np from PyQt5.QtGui import QImage, qRgb __author__ = "Ivan Sevcik" gray_color_table = [qRgb(gctIdx, gctIdx, gctIdx) for gctIdx in range(256)] class NotImplementedException(object): pass def toQImage(im, copy=False): if im is None: return QImage() if im.dtype == np.uint8: if len(im.shape) == 2: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8) qim.setColorTable(gray_color_table) return qim.copy() if copy else qim elif len(im.shape) == 3: if im.shape[2] == 3: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888) return qim.copy() if copy else qim elif im.shape[2] == 4: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32) return qim.copy() if copy else qim raise NotImplementedException
def rgb(r, g, b): # use qRgb to pack the colors, and then turn the resulting long # into a negative integer with the same bitpattern. return (qRgb(r, g, b) & 0xffffff) - 0x1000000
def run(self): while True: self.mutex.lock() resultSize = self.resultSize scaleFactor = self.scaleFactor centerX = self.centerX centerY = self.centerY self.mutex.unlock() halfWidth = resultSize.width() // 2 halfHeight = resultSize.height() // 2 image = QImage(resultSize, QImage.Format_RGB32) NumPasses = 8 curpass = 0 while curpass < NumPasses: MaxIterations = (1 << (2 * curpass + 6)) + 32 Limit = 4 allBlack = True for y in range(-halfHeight, halfHeight): if self.restart: break if self.abort: return ay = 1j * (centerY + (y * scaleFactor)) for x in range(-halfWidth, halfWidth): c0 = centerX + (x * scaleFactor) + ay c = c0 numIterations = 0 while numIterations < MaxIterations: numIterations += 1 c = c*c + c0 if abs(c) >= Limit: break numIterations += 1 c = c*c + c0 if abs(c) >= Limit: break numIterations += 1 c = c*c + c0 if abs(c) >= Limit: break numIterations += 1 c = c*c + c0 if abs(c) >= Limit: break if numIterations < MaxIterations: image.setPixel(x + halfWidth, y + halfHeight, self.colormap[numIterations % RenderThread.ColormapSize]) allBlack = False else: image.setPixel(x + halfWidth, y + halfHeight, qRgb(0, 0, 0)) if allBlack and curpass == 0: curpass = 4 else: if not self.restart: self.renderedImage.emit(image, scaleFactor) curpass += 1 self.mutex.lock() if not self.restart: self.condition.wait(self.mutex) self.restart = False self.mutex.unlock()
def clearImage(self): self.image.fill(qRgb(255, 255, 255)) self.modified = True self.update()
jbf_file = sys.argv[1] png_file = sys.argv[2] data = open(jbf_file, "rb").read() x_offset = struct.unpack(">H", data[8:10])[0] length = struct.unpack(">I", data[20:24])[0] width, height = struct.unpack("<II", data[24 + length + 4:24 + length + 12]) padding = (4 - (width % 4)) % 4 i = 24 + x_offset thumbnail_data = "" entries = set() for j in range(height): row = data[i:i + width] + (padding * "\x00") for k in row: entries.add(ord(k)) thumbnail_data += row i += width image = QImage(thumbnail_data, width, height, QImage.Format_Indexed8) image.setColorTable(range(max(entries) + 1)) for entry in entries: image.setColor(entry, qRgb(0, 0, 0)) image.setColor(0, qRgb(255, 255, 255)) image.save(png_file) sys.exit()
''' This fname provides all the constants and enums other files need to share. Author: Philippe Fremy License: Gnu GPL (see fname LICENSE) ''' from typing import Dict, List from PyQt5.QtGui import qRgb from PyQt5.QtCore import Qt VERSION = '1.3.2' TILE_SIZE = 32 TRANSP_COLOR = qRgb(0, 0, 0) ID_SPLASH_SCREEN = 0 NAME_SPLASH_SCREEN = 'Splash' PIX_SIZE = TILE_SIZE // 2 MINI_TILE_SIZE = 4 TILE_FILE_NAME = "klotski-tiles.png" MSG_ABOUT = ("""Klotski %s by Philippe Fremy <*****@*****.**> Graphics by Ben Adler <[email protected] Klotski is the reborn version of a game existing under Windows 3.1 . This is where all the levels are coming from.
class Image(QImage): """ Class to hold a single image from a file-read or a numpy.array. """ gray_color_table = [qRgb(i, i, i) for i in range(256)] #################################################################################################################### def __init__(self, array: np.ndarray = None, path: str = None, file_name: str = None, **kwargs): """ :param path: full path to file folder :param file_name: name of image file :param kwargs: RESERVED """ if array is not None: self.__array_to_q_image(im=array) self.__name = 'from_array' else: if path is not None: file_name = path + file_name # create object with constructor of parent class super().__init__(file_name) self.__name = ntpath.basename(file_name) #################################################################################################################### def get_name(self) -> str: """ :return: file name """ return self.__name #################################################################################################################### def get_pixel_value(self, x: int, y: int) -> tuple: """ :param x: row pixel :param y: col pixel :return: RGB value for an RBG image, grayscale value for a grayscale image """ val = self.pixel(x, y) if self.format() == QImage.Format_ARGB32 or self.format( ) == QImage.Format_RGB32: return QColor(val).getRgb() if self.format() == QImage.Format_Indexed8: return QColor(val).value() raise NotImplementedException #################################################################################################################### def __array_to_q_image(self, im: np.ndarray, copy=False) -> None: """ A method to convert an underlying numpy array of image data into a QImage object. :param im: numpy.ndarray of image data :param copy: boolean to copy underlying array :return: None """ if im is None: self = QImage() if im.dtype == np.uint8: if len(im.shape) == 2: super().__init__(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8) self.setColorTable(Image.gray_color_table) return elif len(im.shape) == 3: if im.shape[2] == 3: super().__init__(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888) return elif im.shape[2] == 4: super().__init__(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32) return raise NotImplementedException #################################################################################################################### @staticmethod def __get_file_ext(file_name) -> FileExt: """ :param file_name: file name :return: file extension """ file_ext = os.path.splitext(file_name)[-1] file_ext_enum = 0 if ('jpg' in file_ext) or ('JPG' in file_ext): file_ext_enum = FileExt.JPEG if ('tif' in file_ext) or ('TIF' in file_ext): file_ext_enum = FileExt.TIF if ('png' is file_ext) or ('PNG' in file_ext): file_ext_enum = FileExt.PNG return file_ext_enum
def updateMask(control_image_path, rendered_image_path, mask_image_path): control_image = imageFromPath(control_image_path) if not control_image: error('Could not read control image {}'.format(control_image_path)) rendered_image = imageFromPath(rendered_image_path) if not rendered_image: error('Could not read rendered image {}'.format(rendered_image_path)) if not rendered_image.width() == control_image.width( ) or not rendered_image.height() == control_image.height(): print( ('Size mismatch - control image is {}x{}, rendered image is {}x{}'. format(control_image.width(), control_image.height(), rendered_image.width(), rendered_image.height()))) max_width = min(rendered_image.width(), control_image.width()) max_height = min(rendered_image.height(), control_image.height()) # read current mask, if it exist mask_image = imageFromPath(mask_image_path) if mask_image.isNull(): print('Mask image does not exist, creating {}'.format(mask_image_path)) mask_image = QImage(control_image.width(), control_image.height(), QImage.Format_ARGB32) mask_image.fill(QColor(0, 0, 0)) # loop through pixels in rendered image and compare mismatch_count = 0 linebytes = max_width * 4 for y in range(max_height): control_scanline = control_image.constScanLine(y).asstring(linebytes) rendered_scanline = rendered_image.constScanLine(y).asstring(linebytes) mask_scanline = mask_image.scanLine(y).asstring(linebytes) for x in range(max_width): currentTolerance = qRed( struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0]) if currentTolerance == 255: # ignore pixel continue expected_rgb = struct.unpack('I', control_scanline[x * 4:x * 4 + 4])[0] rendered_rgb = struct.unpack('I', rendered_scanline[x * 4:x * 4 + 4])[0] difference = colorDiff(expected_rgb, rendered_rgb) if difference > currentTolerance: # update mask image mask_image.setPixel(x, y, qRgb(difference, difference, difference)) mismatch_count += 1 if mismatch_count: # update mask mask_image.save(mask_image_path, "png") print('Updated {} pixels in {}'.format(mismatch_count, mask_image_path)) else: print('No mismatches in {}'.format(mask_image_path))
def clearImage(self): self.image.fill(qRgb(255, 255, 255)) self.update()