def draw_image(self, x, y, width, height, path, crop=None): image = QImage(path) rect = QRectF(self.pts(x), self.pts(y), self.pts(width), self.pts(height)) if crop is None: self.painter.drawImage(rect, image) else: sx, sy, sw, sh = crop source_rect = QRectF( sx * image.width(), sy * image.height(), sw * image.width(), sh * image.height(), ) self.painter.drawImage(rect, image, source_rect)
def setup_category_view(self): self.current_view = StepViews.CATEGORY_VIEW i, j = 0, 0 for category in self.categories: data = urllib.request.urlopen(category["icons"][0]["url"]).read() label = ClickableLabel(self) label.setScaledContents(True) label.setFixedSize(190, 190) label.dataId = category["id"] label.clicked.connect(self.category_click) image = QImage(32, 32, QImage.Format_RGB32) image.loadFromData(data) painter = QPainter(image) painter.setPen(QPen(QColor("white"))) painter.setFont(QFont("Roboto", 22, QFont.Bold)) painter.drawText(QRect(0, 0, image.width(), image.height() - 25), Qt.AlignCenter | Qt.AlignBottom, category["name"]) painter.end() pixmap = QPixmap(image) label.setPixmap(pixmap) self.layout.addWidget(label, i, j) j += 1 if j % 4 == 0: i += 1 j = 0
def scaleImage(self, pixels, path): dircache = QDir(self.mDir + QDir.separator() + "imagecache") if dircache.exists() == False: s = QDir(self.mDir) s.mkdir("imagecache") ima = QImage(path) wids = ima.width() heis = ima.height() if (wids > pixels or heis > pixels): imarescale = ima.scaledToWidth( pixels, Qt.SmoothTransformation) if ( wids > heis) else ima.scaledToHeight( pixels, Qt.SmoothTransformation) newImagePath = dircache.path() + QDir.separator( ) + "_temp_scaled_" + QFileInfo(path).fileName() imawriter = QImageWriter() imawriter.setFileName(newImagePath) # imawriter.setFormat("png"); if (imawriter.write(imarescale)): #qDebug()<<"si path"<<newImagePath return newImagePath else: #qDebug()<<"no path"<<newImagePath; return path return path
def show_image(self, pattern, use_grayscale=False, alpha=0, beta=0, gamma=0): # if not self.connected: # self.print_text_signal.emit("Impossible to show image: projector is not connected!") # return loaded_image = QImage(pattern).convertToFormat( QImage.Format.Format_RGB32) values = loaded_image.bits() pixel_values = np.array(values).reshape(loaded_image.height(), loaded_image.width(), 4) if use_grayscale: thickness = DLPColorCalibrator.my_log_function( 1, alpha, beta, gamma) tmp, corrected_values = DLPColorCalibrator.my_color_correction( pixel_values, alpha, beta, gamma, thickness) corrected_values_tr = corrected_values.copy() corrected_image = QImage(corrected_values_tr, corrected_values_tr.shape[1], corrected_values_tr.shape[0], QImage.Format_RGB32) self.img = QPixmap(corrected_image) else: self.img = QPixmap(loaded_image) if self.horizontal_mirror: self.img = self.img.transformed(QTransform().scale(-1, 1)) if self.vertical_mirror: self.img = self.img.transformed(QTransform().scale(1, -1)) self.display_image_signal.emit(self.img) self.setPixmap(self.img)
def qimage_to_numpy(self, image: QImage) -> Image: image = image.convertToFormat(QImage.Format.Format_RGB32) width = image.width() height = image.height() ptr = image.constBits() arr = np.array(ptr).reshape((height, width, 4))[:, :, :3] return arr
def setImage(self, dir): img = QImage(dir) self.img_w = img.width() self.img_h = img.height() self.img = cv2.imread(dir) self.qp.begin(self.backView) self.qp.drawImage(self.backView.rect(), img) self.qp.end()
def QImageToCV(image: QImage) -> ndarray: if image.format() != QImage.Format_RGB888: image = image.convertToFormat(QImage.Format_RGB888) width = image.width() height = image.height() ptr = image.bits() arr = array(ptr).reshape(height, width, 3) return arr
def __init__(self, object_set: int, palette_index: int): png = QImage(str(data_dir.joinpath("gfx.png"))) png.convertTo(QImage.Format_RGB888) rows_per_object_set = 256 // 64 y_offset = 12 * rows_per_object_set * Block.HEIGHT self.png_data = png.copy(QRect(0, y_offset, png.width(), png.height() - y_offset)) self.palette_group = load_palette_group(object_set, palette_index)
def testImage(): width, height = 100, 100 im = QImage(width, height, QImage.Format_ARGB32) for x in range(im.width()): for y in range(im.height()): if x % 2 == 0: im.setPixel(x, y, QColor('white').rgb()) else: im.setPixel(x, y, QColor('black').rgb()) # im.setPixel(x, y, QColor(255, x*2.56, y*2.56, 255).rgb()) im.save('test.png')
def display_diff(actual_image: QImage, diff_image: QImage, expected_image: QImage, diff_count: int): # Display image when in live turtle mode. display_image = getattr(turtle.Turtle, 'display_image', None) if display_image is None: return t = turtle.Turtle() # noinspection PyUnresolvedReferences screen = t.screen # type: ignore w = screen.cv.cget('width') h = screen.cv.cget('height') ox, oy = w / 2, h / 2 text_space = (h - actual_image.height() - diff_image.height() - expected_image.height()) text_height = max(20, text_space // 3) font = ('Arial', text_height // 2, 'Normal') t.penup() t.goto(-ox, oy) t.right(90) t.forward(text_height) t.write(f'Actual', font=font) display_image(ox + t.xcor(), oy - t.ycor(), image=encode_image(actual_image)) t.forward(actual_image.height()) t.forward(text_height) t.write(f'Diff ({diff_count} pixels)', font=font) display_image(ox + t.xcor(), oy - t.ycor(), image=encode_image(diff_image)) t.forward(diff_image.height()) t.forward(text_height) t.write('Expected', font=font) display_image(ox + t.xcor(), oy - t.ycor(), image=encode_image(expected_image)) t.forward(expected_image.height())
def show_image(self, cv_image): self.resize(200, 200) rgb_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB) h, w, ch = rgb_image.shape bytes_per_line = ch * w qt_image = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888) img_w = qt_image.width() img_h = qt_image.height() proportion = img_w / img_h self.resize(self.width() * proportion, self.height()) qt_image = qt_image.scaled(self.width(), self.height()) self.setPixmap(QPixmap(qt_image)) self.parent_node_instance.update_shape()
def requestImage(self, url, size, requestedSize): url = QUrl(url) image = QImage(url.toLocalFile()) width, height = image.width(), image.height() if size: size.setWidth(width) size.setHeight(height) if requestedSize.width() > 0: width = requestedSize.width() if requestedSize.height() > 0: height = requestedSize.height() return image.scaled(min(width, THUMBNAIL_SIZE), min(height, THUMBNAIL_SIZE), Qt.KeepAspectRatio)
def initUI(self): image = QImage(self.file_name) if image.width() > image.height(): pixmap = QPixmap(image.scaledToWidth(self.length_max)) else: pixmap = QPixmap(image.scaledToHeight(self.length_max)) label = QLabel(self) label.setPixmap(pixmap) vbox = QVBoxLayout(self) vbox.addWidget(label) vbox.setSizeConstraint(QLayout.SetFixedSize) self.setLayout(vbox)
def create_top_header_qlabel(): qlabel = QLabel() path = Path.cwd() / "metarch/ressources/antares_header_05.png" print("is file = ", path.is_file()) print("path = ", path) if path.is_file(): image = QImage(str(path)) print("image = ", image) print("images height = ", image.height()) qpixmap = QPixmap(image) qlabel.setPixmap(qpixmap) # qlabel.setGeometry(0, 0, 809, 359) return qlabel else: print("ERROR ! Cannot find file for QImage") return None
def __load_image(self, data): # type: (QByteArray) -> None """Creates and caches the QImage from the data. :param data: the data returned by the network request for the image """ image = QImage() loaded = image.loadFromData(data) if loaded: width = image.width() height = image.height() size = (width, height) centre_x = width / 2 centre_y = height / 2 centre = (centre_x, centre_y) _IMAGE_CACHE[self] = image _PIXMAP_CACHE[self] = {} # Cache the full-size pixmap get_pixmap(self, centre, size, size)
def qimg_to_rgb_arr(qimg: QImage) -> RGBArrayF: """Convert a :class:`QtGui.QImage` to an :data:`RGBArrayF` """ fmt = QImage.Format_RGB32 if qimg.format() != fmt: qimg = qimg.convertToFormat(fmt) width, height = qimg.width(), qimg.height() num_pixels = width * height bfr = qimg.constBits() int_arr = np.frombuffer(bfr, dtype=np.uint8, count=num_pixels * 4) bgra_arr = int_arr.reshape((height, width, 4)) / 255 # Format_RGB32 stored as 0xffRRGGBB # so take only the first 3 items but in reverse rgb_arr = bgra_arr[..., 2::-1] return rgb_arr
def __init__( self, image: QtGui.QImage, rect: QtCore.QRectF, smooth: bool = False, snap: bool = True, parent: QtWidgets.QGraphicsItem = None, ): super().__init__(parent) self.setCacheMode( QtWidgets.QGraphicsItem.DeviceCoordinateCache ) # Speed up redraw of image if smooth: self.image = image.scaledToHeight( image.height() * 2, QtCore.Qt.SmoothTransformation ) self.image_scale = 2 else: self.image = image self.image_scale = 1 self.rect = QtCore.QRectF(rect) # copy the rect self.snap = snap
def populateScene(self): self.scene = QGraphicsScene(self) image = QImage(":/qt4logo.png") xx: int = 0 nitems: int = 0 for i in range(-11000, 11000, 110): xx += 1 yy: int = 0 for j in range(-7000, 7000, 70): yy += 1 x = (i + 11000) / 22000.0 y = (j + 7000) / 14000.0 color = QColor( image.pixel(int(image.width() * x), int(image.height() * y))) item = Chip(color, xx, yy) item.setPos(QPointF(i, j)) self.scene.addItem(item) nitems += 1
def saveYoloFormat(self, filename, shapes, imagePath, imageData, classList, 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 = YOLOWriter(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, classList=classList) return
class Mp4Sink: """A QRemoteDesktop Mock.""" def __init__(self): self._buffer: QImage = None @property def screen(self): return self._buffer def notifyImage(self, x: int, y: int, img: QImage, w: int, h: int): p = QPainter(self._buffer) p.drawImage(x, y, img, 0, 0, w, h) def resize(self, w: int, h: int): self._buffer = QImage(w, h, QImage.Format_ARGB32_Premultiplied) def width(self) -> int: return self._buffer.width() def height(self) -> int: return self._buffer.height() def update(self): pass
class GalleryMiniature(QDialog): def __init__(self, pid=0, filename=0): super().__init__() #self.resize(800,600) self.pid = pid #print(filename) self.filename = filename layout = QHBoxLayout() self.baseLabel = MovableLabel() self.baseLabel.setFrameShape(QFrame.StyledPanel) self.baseLabel.setAlignment(Qt.AlignCenter) self.baseLabel.getRectCoords.connect(self.getRectCoordsSlot) self.miniLabel = QLabel() self.miniLabel.setAlignment(Qt.AlignCenter) self.base_image = QImage() self.mini_image = QImage() self.base_image_scaled = 0 #self.filename = 0 self.pix = 0 self.currentIndex = 0 self.real_size = 0 layout.addWidget(self.baseLabel) layout.addWidget(self.miniLabel) def openMenu(position): menu = QMenu() openAction = menu.addAction('Открыть') saveAction = menu.addAction('Сохранить') menu.addSeparator() nextAction = menu.addAction('Следующий') menu.addSeparator() quitAction = menu.addAction('Выход') action = menu.exec_(self.mapToGlobal(position)) if action == openAction: fileName = QFileDialog.getOpenFileName( self, "Изображение", "photos", "Фото (*.png *.jpg *.bmp *.JPG)") if len(fileName) > 1: self.filename = fileName[0] self.show_images() if action == saveAction: if self.filename: print('os.path.basename(self.filename)') path = os.path.basename(self.filename) root_ext = os.path.splitext(path) print(root_ext) if self.pid: root_ext = [str(pid) + '_001'] minifile = os.path.join( os.path.join('photos', 'miniatures'), root_ext[0] + '.png') if self.pix: self.pix.save(minifile, "PNG") print(minifile) if action == nextAction: if self.base_image: self.get_face_image() if action == quitAction: self.close() self.setContextMenuPolicy(Qt.CustomContextMenu) self.customContextMenuRequested.connect(openMenu) self.setLayout(layout) if self.filename: self.show_images() else: screen = QGuiApplication.primaryScreen() screenSize = screen.availableSize() sy = int((screenSize.height() - 20) / 4) sx = int((screenSize.width() - 20) / 4) self.setGeometry(sx, sy, int(screenSize.width() / 4), int(screenSize.height() / 4)) def show_images(self): #print(self.filename) self.base_image.load(self.filename) self.real_size = (self.base_image.width(), self.base_image.height()) screen = QGuiApplication.primaryScreen() screenSize = screen.availableSize() sy = int((screenSize.height() - 20) / 2) sx = int((screenSize.width() - 20) / 2) if not self.base_image_scaled: self.base_image_scaled = self.base_image.scaled( sx, sy, Qt.KeepAspectRatio) self.setGeometry(sx - int(self.base_image_scaled.width()), sy - int(self.base_image_scaled.height() / 2), self.base_image_scaled.width() * 2, self.base_image_scaled.height()) else: self.base_image_scaled = self.base_image.scaled( int(self.base_image_scaled.width()), int(self.base_image_scaled.height()), Qt.KeepAspectRatio) self.setGeometry(sx - int(self.base_image_scaled.width()), sy - int(self.base_image_scaled.height() / 2), self.base_image_scaled.width() * 2, self.base_image_scaled.height()) self.baseLabel.setPixmap(QPixmap.fromImage(self.base_image_scaled)) #self.miniLabel.setPixmap(QPixmap.fromImage(self.base_image)) self.get_face_image() def getRectCoordsSlot(self, coords): print(coords) if self.base_image: self.get_face_image(coords) def get_round_miniature(self, image): size = (300, 300) img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) im = Image.fromarray(img) #im = image #Image.open(image.png) im = crop(im, size) im.putalpha(prepare_mask(size, 4)) #im.save(filename) qim = ImageQt(im) self.pix = QPixmap.fromImage(qim) self.miniLabel.setPixmap(self.pix) #self.miniature = QImage(filename) def get_face_image(self, coords=0): with open(self.filename, 'rb') as f: chunk = f.read() chunk_arr = np.frombuffer(chunk, dtype=np.uint8) image = cv2.imdecode(chunk_arr, cv2.IMREAD_COLOR) if coords == 0: print(self.filename) #image = cv2.imread(self.filename) # !!!!!!!!!!!! Обязательно указать правильный путь к файлу !!!!!!!!!!!! # !!!!!!!!!!!! Путь до xml есть в https://github.com/opencv/opencv/tree/master/data/haarcascades !!!!!!!!!!!! face_cascade = cv2.CascadeClassifier( os.path.join('xml', 'haarcascade_frontalface_default.xml')) # !!!!!!!!!!!! Необходимо настроить параметры так как находит не все лица !!!!!!!!!!!! faces_coord = face_cascade.detectMultiScale(image, scaleFactor=1.2, minNeighbors=5, minSize=(110, 110)) if (len(faces_coord) > 0): for i, face in enumerate(faces_coord): (x, y, w, h) = face height, width, channels = image.shape s = int(min(width * 0.1, height * 0.1)) if y - s >= 0: y = y - s h = h + s if x - s >= 0: x = x - s w = w + s h = h + s if y + h + s < height else h w = w + s if x + w + s < width else w if i == self.currentIndex: crop_image = image[y:y + h, x:x + w] #cv2.imshow("Face", crop_image) self.get_round_miniature(crop_image) break #cv2.waitKey(0) #crop_image.save() self.currentIndex = 0 if self.currentIndex + 1 >= len( faces_coord) else self.currentIndex + 1 else: if self.real_size: #image = cv2.imread(self.filename) #x_scale = self.base_image.width() / self.base_image_scaled.width() #y_scale = self.base_image.height() / self.base_image_scaled.height() x_scale = self.base_image.width( ) * self.base_image_scaled.width() / ( self.base_image_scaled.width() * self.baseLabel.width()) y_scale = self.base_image.height( ) * self.base_image_scaled.height() / ( self.base_image_scaled.height() * self.baseLabel.height()) print( (int(coords[0][1] * y_scale), int(coords[1][1] * y_scale), int(coords[0][0] * x_scale), int(coords[1][0] * x_scale))) crop_image = image[int(coords[0][1] * y_scale):int(coords[1][1] * y_scale), int(coords[0][0] * x_scale):int(coords[1][0] * x_scale)] self.get_round_miniature(crop_image)
def _draw_scoreboard(self, painter, sizes, voter_num): scale = self.details.scale contest = self.details.contest # Display scoreboard background rectangle self._draw_rectangle(painter, QPoint(0, 0), QPoint(sizes.width, sizes.height), self.colors.light_grey) # Display voter details self._draw_rectangle(painter, QPoint(0, 0), QPoint(sizes.width, 30 * scale), self.colors.main) self._draw_text( painter, QPoint(10 * scale, 15 * scale), "Now Voting: {} ({}/{})".format(contest.voters[voter_num], voter_num + 1, contest.num_voters), self.fonts.voter_header, self.colors.white_text, Qt.AlignLeft) # Display contest title self._draw_rectangle(painter, QPoint(0, 30 * scale), QPoint(sizes.width, 30 * scale), self.colors.accent) self._draw_text(painter, QPoint(10 * scale, 45 * scale), "{} Results".format(self.details.title), self.fonts.contest_header, self.colors.accent_text, Qt.AlignLeft) # Draw background rectangles for entry details left_col = int( self.contest.num_entries / 2) + self.contest.num_entries % 2 right_col = self.contest.num_entries - left_col self._draw_rectangle(painter, QPoint(10 * scale, 70 * scale), QPoint(sizes.rectangle, 0 * scale + 35 * scale * left_col), self.colors.white, border=self.colors.grey_text, border_width=0.5 * scale) self._draw_rectangle(painter, QPoint(20 * scale + sizes.rectangle, 70 * scale), QPoint(sizes.rectangle, 0 * scale + 35 * scale * right_col), self.colors.white, border=self.colors.grey_text, border_width=0.5 * scale) entries = self.contest.results_after_voter(voter_num) for i, entry in enumerate(entries): if i < left_col: x_offset = 0 y_offset = i else: x_offset = 10 * scale + sizes.rectangle y_offset = i - left_col # Display the entry's country flag if self.details.display_flags: try: flag = QImage( self.app_context.get_resource(join( "flags", entry.flag))) flag = flag.scaledToWidth(20 * scale, Qt.SmoothTransformation) self._draw_rectangle( painter, QPoint( 27 * scale - flag.width() / 2.0 + x_offset, 87 * scale - flag.height() / 2.0 + 35 * scale * y_offset), QPoint(flag.width() + 0.5, flag.height() + 0.5), self.colors.white, border=self.colors.grey_text, border_width=0.5 * scale) painter.drawImage( QPoint( 27 * scale - flag.width() / 2.0 + x_offset, 87 * scale - flag.height() / 2.0 + 35 * scale * y_offset), flag) except FileNotFoundError: continue # Display entry details self._draw_text( painter, QPoint(20 * scale + x_offset + sizes.flag_offset, 80 * scale + 35 * scale * y_offset), entry.country, self.fonts.country, self.colors.country_text, Qt.AlignLeft) self._draw_text( painter, QPoint(20 * scale + x_offset + sizes.flag_offset, 94 * scale + 35 * scale * y_offset), "{} – {}".format(entry.artist, entry.song), self.fonts.entry_details, self.colors.black, Qt.AlignLeft) # Display the entry's total number of received points if entry.dq_statuses[voter_num]: self._draw_rectangle( painter, QPoint( 30 * scale + x_offset + sizes.flag_offset + sizes.entry_details, 77 * scale + 35 * scale * y_offset), QPoint(29 * scale, 20 * scale), self.colors.grey_text) self._draw_text( painter, QPoint( 44.5 * scale + x_offset + sizes.flag_offset + sizes.entry_details, 87 * scale + 35 * scale * y_offset), "{}".format(entry.display_pts[voter_num]), self.fonts.total_pts, self.colors.black, Qt.AlignHCenter) else: self._draw_rectangle( painter, QPoint( 30 * scale + x_offset + sizes.flag_offset + sizes.entry_details, 77 * scale + 35 * scale * y_offset), QPoint(29 * scale, 20 * scale), self.colors.main) self._draw_text( painter, QPoint( 44.5 * scale + x_offset + sizes.flag_offset + sizes.entry_details, 87 * scale + 35 * scale * y_offset), "{}".format(entry.display_pts[voter_num]), self.fonts.total_pts, self.colors.white_text, Qt.AlignHCenter) # Display the entry's number of points received by the current voter if len(entry.votes[voter_num]) > 0: self._draw_rectangle( painter, QPoint( 59 * scale + x_offset + sizes.flag_offset + sizes.entry_details, 77 * scale + 35 * scale * y_offset), QPoint(24 * scale, 20 * scale), self.colors.accent) try: votes_string = int(float(entry.votes[voter_num])) except ValueError: votes_string = entry.votes[voter_num] self._draw_text( painter, QPoint( 71 * scale + x_offset + sizes.flag_offset + sizes.entry_details, 87 * scale + 35 * scale * y_offset), str(votes_string), self.fonts.awarded_pts, self.colors.accent_text, Qt.AlignHCenter) # Draw a dividing line between entries if i + 1 != left_col and i + 1 != self.contest.num_entries: painter.setPen(QPen(self.colors.grey_text, 0.5 * scale)) painter.drawLine( QPoint(10 * scale + x_offset, 104.5 * scale + 35 * scale * y_offset), QPoint(10 * scale + x_offset + sizes.rectangle, 104.5 * scale + 35 * scale * y_offset))
class View(QWidget): previous = Signal() next = Signal() def __init__(self, window): super(View, self).__init__(window) self.setFocusPolicy(Qt.StrongFocus) self.shiftKey = False self.ctrlKey = False self.lastMousePos = QPoint() self.lastTabletPos = QPoint() self.mode = 'add' self.maskOnly = False self.refresh = QTimer(self) self.refresh.setSingleShot(True) self.refresh.timeout.connect(self.repaint) self.addCursor = makeCursor('images/cursor-add.png', QColor.fromRgbF(0.5, 0.5, 1.0)) self.delCursor = makeCursor('images/cursor-del.png', QColor.fromRgbF(1.0, 0.5, 0.5)) self.setCursor(self.addCursor) self.imagefile = None self.maskfile = None self.image = QImage() self.mask = QImage(self.image.size(), QImage.Format_RGB32) self.mask.fill(Qt.black) self.changed = False self.update() self.path = list() self.load_threads = QThreadPool() self.load_threads.setMaxThreadCount(4) def load(self, filename): self.load_threads.start(LoadTask(self, filename)) def save(self): if self.maskfile and self.changed: self.load_threads.waitForDone() if self.maskfile and self.changed: bitmap = self.mask.createMaskFromColor( QColor.fromRgbF(1.0, 0.0, 1.0).rgb()) bitmap.save(str(self.maskfile), "PNG") self.changed = False def update(self): widgetRatio = self.width() / self.height() aspectRatio = self.image.width() / max(1, self.image.height()) if aspectRatio >= widgetRatio: width = self.width() height = self.width() / aspectRatio else: width = self.height() * aspectRatio height = self.height() self.rc = QRectF((self.width() - width) / 2.0, (self.height() - height) / 2.0, width, height) self.repaint() def resizeEvent(self, event): self.update() def paintEvent(self, event): p = QPainter(self.mask) for (mode, p1, p2, weight) in self.path: if mode == 'add': p.setPen( QPen(QColor.fromRgbF(1.0, 0.0, 1.0), (weight * 10.0)**2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) else: p.setPen( QPen(QColor.fromRgbF(0.0, 0.0, 0.0), (weight * 10.0)**2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) p.drawLine(realCoords(p1, self.mask.rect()), realCoords(p2, self.mask.rect())) self.changed = True self.path = list() p.end() p = QPainter(self) p.setCompositionMode(QPainter.CompositionMode_SourceOver) if not self.maskOnly: p.drawImage(self.rc, self.image) p.setCompositionMode(QPainter.CompositionMode_Plus) p.drawImage(self.rc, self.mask) p.end() def closeEvent(self, event): self.refresh.stop() event.accept() def enterEvent(self, event): self.setFocus(Qt.OtherFocusReason) def keyPressEvent(self, event): k = event.key() if k == Qt.Key_Shift: self.shiftKey = True if k == Qt.Key_Control: self.ctrlKey = True if k == Qt.Key_Space: self.maskOnly = not self.maskOnly self.repaint() def keyReleaseEvent(self, event): k = event.key() mod = event.modifiers() if k == Qt.Key_Shift: self.shiftKey = False if k == Qt.Key_Control: self.ctrlKey = False def mousePressEvent(self, event): x = event.x() y = event.y() self.lastMousePos = event.pos() if event.button() == Qt.ExtraButton1: if self.mode == 'add': self.mode = 'del' self.setCursor(self.delCursor) else: self.mode = 'add' self.setCursor(self.addCursor) elif event.button() == Qt.ExtraButton2: self.maskOnly = not self.maskOnly self.repaint() elif event.button() == Qt.ExtraButton3: self.previous.emit() elif event.button() == Qt.ExtraButton4: self.next.emit() def mouseMoveEvent(self, event): x = event.x() y = event.y() dx = x - self.lastMousePos.x() dy = y - self.lastMousePos.y() self.lastMousePos = event.pos() # if event.buttons() & Qt.LeftButton: # elif event.buttons() & Qt.MiddleButton: # elif event.buttons() & Qt.RightButton: def wheelEvent(self, event): dx = event.angleDelta().x() / 8 dy = event.angleDelta().y() / 8 # self.cameraZoom.emit(dy / 15) def tabletEvent(self, event): if event.device() == QTabletEvent.Stylus and event.pointerType( ) == QTabletEvent.Pen: if event.type() == QEvent.TabletPress: self.tabletPressEvent(event) elif event.type() == QEvent.TabletRelease: self.tabletReleaseEvent(event) elif event.type() == QEvent.TabletMove: if event.pressure() > 0.0: self.tabletMoveEvent(event) else: print('tabletEvent', event.device(), event.type(), event.pointerType()) else: print('tabletEvent', event.device(), event.type(), event.pointerType()) def tabletPressEvent(self, event): if event.buttons() & Qt.LeftButton: self.lastTabletPos = normalizeCoords(event.posF(), self.rc) if event.buttons() & Qt.MiddleButton: if self.mode == 'add': self.mode = 'del' self.setCursor(self.delCursor) else: self.mode = 'add' self.setCursor(self.addCursor) if event.buttons() & Qt.RightButton: self.next.emit() def tabletReleaseEvent(self, event): self.lastTabletPos = normalizeCoords(event.posF(), self.rc) def tabletMoveEvent(self, event): self.path.append((self.mode, self.lastTabletPos, normalizeCoords(event.posF(), self.rc), event.pressure())) self.lastTabletPos = normalizeCoords(event.posF(), self.rc) if not self.refresh.isActive(): self.refresh.start(50)
class Picture(object): def __init__(self, path): super(Picture, self).__init__() self.path = path self.name = self.path.split("/")[-1] self.extension = os.path.splitext(self.path)[1] self.scale = 1.0 self.image = QImage(self.path) self.thumbnail = self.image.scaled(QSize(110, 110), aspectMode=Qt.KeepAspectRatio, mode=Qt.SmoothTransformation) self.resolution = "Resolution: " + str(self.image.width()) + "x" + str( self.image.height()) + "px" def deletePicture(self): os.remove(self.path) def verticalFlip(self): self.image = self.image.mirrored(vertically=True, horizontally=False) self.thumbnail = self.image.scaled(QSize(110, 110), aspectMode=Qt.KeepAspectRatio, mode=Qt.SmoothTransformation) self.image.save(self.path) def horizontalFlip(self): self.image = self.image.mirrored(horizontally=True, vertically=False) self.thumbnail = self.image.scaled(QSize(110, 110), aspectMode=Qt.KeepAspectRatio, mode=Qt.SmoothTransformation) self.image.save(self.path) def zoomIn(self): self.scale = self.scale * 0.9 def zoomOut(self): self.scale = self.scale * 1.1 def rotateCW(self): transform = QTransform() transform.translate(self.image.width() / 2, self.image.height() / 2) transform.rotate(90) self.image = self.image.transformed(transform) self.image.save(self.path) self.thumbnail = self.image.scaled(QSize(110, 110), aspectMode=Qt.KeepAspectRatio, mode=Qt.SmoothTransformation) def rotateCCW(self): transform = QTransform() transform.translate(self.image.width() / 2, self.image.height() / 2) transform.rotate(-90) self.image = self.image.transformed(transform) self.image.save(self.path) self.thumbnail = self.image.scaled(QSize(110, 110), aspectMode=Qt.KeepAspectRatio, mode=Qt.SmoothTransformation) def saveImage(self): self.image.save(self.path)
def _test_pipedimagerpq(): # vertices of a pentagon (roughly) centered in a 1000 x 1000 square pentagonpts = ( (504.5, 100.0), (100.0, 393.9), (254.5, 869.4), (754.5, 869.4), (909.0, 393.9), ) linepts = ((350, 50), (200, 150), (400, 250), (300, 350), (150, 250), (100, 450)) # start PyQt testapp = QApplication(["PipedImagerPQ"]) # create the list of commands to submit drawcmnds = [] drawcmnds.append({"action": "setTitle", "title": "Tester"}) drawcmnds.append({"action": "show"}) drawcmnds.append({"action": "clear", "color": "black"}) drawcmnds.append({"action": "screenInfo"}) # create the image to be displayed testimage = QImage(500, 500, QImage.Format_ARGB32_Premultiplied) # initialize a black background testimage.fill(0xFF000000) # draw some things in the image testpainter = QPainter(testimage) testpainter.setBrush(QBrush(QColor(0, 255, 0, 128), Qt.SolidPattern)) testpainter.setPen( QPen(QBrush(QColor(255, 0, 0, 255), Qt.SolidPattern), 5.0, Qt.SolidLine, Qt.SquareCap, Qt.MiterJoin)) testpainter.drawRect(QRectF(5.0, 255.0, 240.0, 240.0)) testpainter.setBrush(QBrush(QColor(0, 0, 255, 255), Qt.SolidPattern)) testpainter.setPen( QPen(QBrush(QColor(0, 0, 0, 255), Qt.SolidPattern), 5.0, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin)) testpainter.drawPolygon( QPolygonF([ QPointF(.25 * ptx, .25 * pty + 250) for (ptx, pty) in pentagonpts ])) testpainter.setBrush(Qt.NoBrush) testpainter.setPen( QPen(QBrush(QColor(255, 255, 255, 255), Qt.SolidPattern), 3.0, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin)) testpainter.drawPolyline( QPolygonF([QPointF(pts, pty) for (pts, pty) in linepts])) testpainter.end() # add the image command testimgwidth = testimage.width() testimgheight = testimage.height() testimgstride = testimage.bytesPerLine() # not a good way to get the pixel data testimgdata = bytearray(testimgheight * testimgstride) k = 0 for pty in range(testimgheight): for ptx in range(testimgwidth): pixval = testimage.pixel(ptx, pty) (aval, rgbval) = divmod(pixval, 256 * 256 * 256) (rval, gbval) = divmod(rgbval, 256 * 256) (gval, bval) = divmod(gbval, 256) testimgdata[k] = bval k += 1 testimgdata[k] = gval k += 1 testimgdata[k] = rval k += 1 testimgdata[k] = aval k += 1 testblocksize = 4000 testnumblocks = (testimgheight * testimgstride + testblocksize - 1) // testblocksize drawcmnds.append({ "action": "newImage", "width": testimgwidth, "height": testimgheight, "stride": testimgstride }) for k in range(testnumblocks): if k < (testnumblocks - 1): blkdata = testimgdata[k * testblocksize:(k + 1) * testblocksize] else: blkdata = testimgdata[k * testblocksize:] drawcmnds.append({ "action": "newImage", "blocknum": k + 1, "numblocks": testnumblocks, "startindex": k * testblocksize, "blockdata": blkdata }) # finish the command list drawcmnds.append({"action": "show"}) drawcmnds.append({"action": "exit"}) # create a PipedImagerPQ in this process (cmndrecvpipe, cmndsendpipe) = multiprocessing.Pipe(False) (rspdrecvpipe, rspdsendpipe) = multiprocessing.Pipe(False) testviewer = PipedImagerPQ(cmndrecvpipe, rspdsendpipe) # create a command submitter dialog tester = _CommandSubmitterPQ(testviewer, cmndsendpipe, rspdrecvpipe, drawcmnds) tester.show() # let it all run testresult = testapp.exec_() if testresult != 0: sys.exit(testresult)
class ScribbleArea(QWidget): def __init__(self, parent=None): super(ScribbleArea, self).__init__(parent) self.myPenColors = [ QColor("green"), QColor("purple"), QColor("red"), QColor("blue"), QColor("yellow"), QColor("pink"), QColor("orange"), QColor("brown"), QColor("grey"), QColor("black") ] self.setAttribute(Qt.WA_AcceptTouchEvents) self.setAttribute(Qt.WA_StaticContents) self.image = QImage() self.modified = False def s_print(self): pass def clearImage(self): self.image.fill(qRgb(255, 255, 255)) self.modified = True self.update() def openImage(self, fileName): loadedImage = QImage() if not loadedImage.load(fileName): return False newSize = loadedImage.size().expandedTo(self.size()) self.resizeImage(loadedImage, newSize) self.image = loadedImage self.modified = False self.update() return True def saveImage(self, fileName, fileFormat): visibleImage = self.image.copy() self.resizeImage(visibleImage, self.size()) if visibleImage.save(fileName, fileFormat): self.modified = False return True else: return False def paintEvent(self, event): painter = QPainter(self) rect = event.rect() painter.drawImage(rect.topLeft(), self.image, rect) def resizeEvent(self, event): if self.width() > self.image.width() or self.height( ) > self.image.height(): newWidth = max(self.width() + 128, self.image.width()) newHeight = max(self.height() + 128, self.image.height()) self.resizeImage(self.image, QSize(newWidth, newHeight)) self.update() super(ScribbleArea, self).resizeEvent(event) def resizeImage(self, image, newSize): if self.image.size() == newSize: return newImage = QImage(newSize, QImage.Format_RGB32) newImage.fill(qRgb(255, 255, 255)) painter = QPainter(newImage) painter.drawImage(QPoint(0, 0), self.image) self.image = newImage # # def print(self, ) # { # #ifndef QT_NO_PRINTER: # QPrinter printer(QPrinter.HighResolution) # # QPrintDialog *printDialog = new QPrintDialog(&printer, this) # if (printDialog.exec() == QDialog.Accepted) { # QPainter painter(&printer) # QRect rect = painter.viewport() # QSize size = self.image.size() # size.scale(rect.size(), Qt.KeepAspectRatio) # painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) # painter.setWindow(self.image.rect()) # painter.drawImage(0, 0, image) # } # #endif // QT_NO_PRINTER # } # def event(self, event): if event.type() == QEvent.TouchBegin or event.type( ) == QEvent.TouchUpdate or event.type() == QEvent.TouchEnd: touchPoints = event.touchPoints() for touchPoint in touchPoints: if touchPoint.state() == Qt.TouchPointStationary: continue else: rect = touchPoint.rect() if rect.isEmpty(): diameter = 50 * touchPoint.pressure() rect.setSize(QSizeF(diameter, diameter)) painter = QPainter(self.image) painter.setPen(Qt.NoPen) painter.setBrush(self.myPenColors[touchPoint.id() % len(self.myPenColors)]) painter.drawEllipse(rect) painter.end() self.modified = True rad = 2 self.update(rect.toRect().adjusted(-rad, -rad, +rad, +rad)) else: return super(ScribbleArea, self).event(event) return True
class Bot(QQuickPaintedItem): def __init__(self, parent=None): super(Bot, self).__init__(parent) self._map = None self.image = QImage(300, 300, QImage.Format_RGBA8888) self.image.fill('#000000ff') self.timer = QTimer() self.position = QPoint() self.around = None self.angle = 0 self.last_front = False self.timer.timeout.connect(lambda: self.drawCircle(self.position)) def paint(self, painter): painter.drawImage(QRect(0, 0, self.width(), self.height()), self.image) def setMap(self, map: Map): if not map: return print('Map', map) self._map = map self._map.clicked.connect(self.handleClick) self.image = QImage(self.map.image.width(), self.map.image.height(), QImage.Format_RGBA8888) self.image.fill('#000000ff') def getMap(self) -> Map: return self._map map = Property(Map, getMap, setMap) @Slot(QPoint) def handleClick(self, point: QPoint): self.position = point self.around = False self.drawCircle(point) self.timer.start(100) def mousePressEvent(self, event): a, b = event.pos().x() * self.image.width() / self.width(), event.pos( ).y() * self.image.height() / self.height() def mouseMoveEvent(self, event): a, b = event.pos().x() * self.image.width() / self.width(), event.pos( ).y() * self.image.height() / self.height() @Slot(QPoint) def drawCircle(self, point: QPoint): a = point.x() b = point.y() angle_step_size = 64 radius = 90 initPoint = QPoint(-1, -1) finalPoint = initPoint firstPoint = finalPoint self.image.fill('#000000ff') painter = QPainter(self.image) lidarPoints = [] painter.setPen('#00ff00') painter.drawRect(point.x() - 1, point.y() - 1, 2, 2) front = QPoint(math.cos(self.angle), math.sin(self.angle)) self.image.setPixelColor(point + front, QColor('#0000ff')) painter.setPen('#ff0000') for step in range(0, angle_step_size - 1): angle = 2 * math.pi * step / angle_step_size + self.angle initPoint = finalPoint for r in range(1, radius): x = point.x() + r * math.cos(angle) y = point.y() + r * math.sin(angle) finalPoint = QPoint(x, y) if not self.map.pixel(x, y): break if initPoint != QPoint(-1, -1): painter.drawLine(initPoint, finalPoint) else: firstPoint = finalPoint lidarPoints.append(finalPoint - point) painter.drawLine(finalPoint, firstPoint) painter.end() self.update() self.runObstacleAvoidance(point, lidarPoints) def runObstacleAvoidance(self, point, lidarPoints): # Calculate distance # Target 287, 293 destiny = QPoint(287, 293) ao = destiny - point rcoli = 2 # Get only the front, right, back and left values lpoints = [ lidarPoints[int(i * (len(lidarPoints) + 1) / 4)] for i in range(4) ] dist = lambda d: (d.x()**2 + d.y()**2)**0.5 dist2 = lambda d, d2: ((d.x() - d2.x())**2 + (d.y() - d2.y())**2)**0.5 dists = [dist(p) for p in lpoints] # Calculate next point nextPoint = point if dists[0] < rcoli and not self.around: self.around_point = copy.copy(point) self.around = dists[0] < rcoli or self.around # Bug algorithm if not self.around: if abs(ao.x()) > abs(ao.y()): if ao.x() > 0: nextPoint += QPoint(1, 0) self.angle = 0 else: nextPoint += QPoint(-1, 0) self.angle = math.pi else: if ao.y() > 0: nextPoint += QPoint(0, 1) self.angle = math.pi / 2 else: nextPoint += QPoint(0, -1) self.angle = 3 * math.pi / 2 else: if dist2(self.around_point, point) + dist2(destiny, point) - dist2( destiny, self.around_point) < 3 and dist2( self.around_point, point) > 3: self.around = False elif dists[3] < rcoli: if dists[0] > rcoli: self.position += QPoint(math.cos(self.angle), math.sin(self.angle)) else: self.angle += math.pi / 2 elif dists[0] < rcoli: self.position += QPoint(math.cos(self.angle), math.sin(self.angle)) self.angle += math.pi / 2 elif dists[1] < rcoli: self.angle += math.pi else: self.position += QPoint(math.cos(self.angle - math.pi / 2), math.sin(self.angle - math.pi / 2)) self.angle -= math.pi / 2
def run(self): # next() raises a StopIteration exception when the generator ends. # If this exception is unhandled by run(), it causes thread termination. # If wdg internal C++ object was destroyed by main thread (form closing) # a RuntimeError exception is raised and causes thread termination too. # Thus, no further synchronization is needed. import exiftool with exiftool.ExifTool() as e: while True: try: filename = next(self.fileListGen) # get orientation try: # read metadata from sidecar (.mie) if it exists, otherwise from image file. profile, metadata = e.get_metadata( filename, tags=("colorspace", "profileDescription", "orientation", "model", "rating", "FileCreateDate"), createsidecar=False) except ValueError: metadata = {} # get image info tmp = [ value for key, value in metadata.items() if 'orientation' in key.lower() ] orientation = tmp[ 0] if tmp else 1 # metadata.get("EXIF:Orientation", 1) # EXIF:DateTimeOriginal seems to be missing in many files tmp = [ value for key, value in metadata.items() if 'date' in key.lower() ] date = tmp[ 0] if tmp else '' # metadata.get("EXIF:ModifyDate", '') tmp = [ value for key, value in metadata.items() if 'rating' in key.lower() ] rating = tmp[ 0] if tmp else 0 # metadata.get("XMP:Rating", 5) rating = ''.join(['*'] * int(rating)) transformation = exiftool.decodeExifOrientation( orientation) # get thumbnail img = e.get_thumbNail(filename, thumbname='thumbnailimage') # no thumbnail found : try preview if img.isNull(): img = e.get_thumbNail( filename, thumbname='PreviewImage' ) # the order is important : for jpeg PreviewImage is full sized ! # all failed : open image if img.isNull(): img = QImage(filename) # remove possible black borders, except for .NEF if filename[-3:] not in ['nef', 'NEF']: bBorder = 7 img = img.copy( QRect(0, bBorder, img.width(), img.height() - 2 * bBorder)) pxm = QPixmap.fromImage(img) if not transformation.isIdentity(): pxm = pxm.transformed(transformation) # set item caption and tooltip item = QListWidgetItem( QIcon(pxm), basename(filename)) # + '\n' + rating) item.setToolTip( basename(filename) + ' ' + date + ' ' + rating) # set item mimeData to get filename=item.data(Qt.UserRole)[0] transformation=item.data(Qt.UserRole)[1] item.setData(Qt.UserRole, (filename, transformation)) self.wdg.addItem(item) # for clean exiting we catch all exceptions and force break except OSError: continue except: break
def peek_image(path): im = QImage(path) return im.width(), im.height()
def redoIt(self): maya_cmds.undoInfo(stateWithoutFlush=False) try: image = QImage(self.image) if image.format() != QImage.Format_RGBA8888: image = image.convertToFormat(QImage.Format_RGBA8888) imageBits = image.bits() imageWidth = image.width() imageHeight = image.height() imageWidthM = imageWidth - 1 imageHeightM = imageHeight - 1 mFnMesh = OpenMaya.MFnMesh( OpenMaya.MGlobal.getSelectionListByName( self.shape).getDagPath(0)) mPoints = mFnMesh.getPoints(OpenMaya.MSpace.kWorld) self.mPoints = OpenMaya.MPointArray(mPoints) tmp1, uvIdsFace = mFnMesh.getAssignedUVs(self.uvName) tmp2, vertexIdsFace = mFnMesh.getVertices() u, v = mFnMesh.getUVs(self.uvName) uvs = [0] * len(u) for i in xrange(len(uvIdsFace)): uvIdFace = uvIdsFace[i] uvs[vertexIdsFace[i]] = [u[uvIdFace], v[uvIdFace]] if self.matrixIs.X: diffX = self.matrixMax.X - self.matrixMin.X for i in xrange(len(mPoints)): u = int((uvs[i][0] % 1.0) * imageWidthM) v = int((uvs[i][1] % 1.0) * imageHeightM) mPoints[i].x += ((ord(imageBits[ (u + v * imageWidth) * 4 + self.matrixCha.X]) * diffX) / 255.0) + self.matrixMin.X if self.matrixIs.Y: diffY = self.matrixMax.Y - self.matrixMin.Y for i in xrange(len(mPoints)): u = int((uvs[i][0] % 1.0) * imageWidthM) v = int((uvs[i][1] % 1.0) * imageHeightM) mPoints[i].y += ((ord(imageBits[ (u + v * imageWidth) * 4 + self.matrixCha.Y]) * diffY) / 255.0) + self.matrixMin.Y if self.matrixIs.Z: diffZ = self.matrixMax.Z - self.matrixMin.Z for i in xrange(len(mPoints)): u = int((uvs[i][0] % 1.0) * imageWidthM) v = int((uvs[i][1] % 1.0) * imageHeightM) mPoints[i].z += ((ord(imageBits[ (u + v * imageWidth) * 4 + self.matrixCha.Z]) * diffZ) / 255.0) + self.matrixMin.Z if self.matrixIs.N: diffN = self.matrixMax.N - self.matrixMin.N mNormals = mFnMesh.getVertexNormals(True, OpenMaya.MSpace.kWorld) for i in xrange(len(mPoints)): u = int((uvs[i][0] % 1.0) * imageWidthM) v = int((uvs[i][1] % 1.0) * imageHeightM) mPoints[i].x += mNormals[i].x * (( (ord(imageBits[ (u + v * imageWidth) * 4 + self.matrixCha.N]) * diffN) / 255.0) + self.matrixMin.N) mPoints[i].y += mNormals[i].y * (( (ord(imageBits[ (u + v * imageWidth) * 4 + self.matrixCha.N]) * diffN) / 255.0) + self.matrixMin.N) mPoints[i].z += mNormals[i].z * (( (ord(imageBits[ (u + v * imageWidth) * 4 + self.matrixCha.N]) * diffN) / 255.0) + self.matrixMin.N) mFnMesh.setPoints(mPoints, OpenMaya.MSpace.kWorld) mFnMesh.updateSurface() except Exception as e: print >> stderr, str(e) maya_cmds.undoInfo(stateWithoutFlush=True)