def save_as(self): #另存为文件,并且将软件重新绑定图片文件路径 fileName_choose, filetype = QFileDialog.getSaveFileName( self, "文件保存", "./", "Bitmap Files (*.bmp);;JPG (*.jpg);;PNG (*.png);;All Files (*)") if fileName_choose == "": #print("\n取消选择") return #print(fileName_choose) if fileName_choose.endswith("bmp")==False \ and fileName_choose.endswith("BMP")==False \ and fileName_choose.endswith("jpg")==False \ and fileName_choose.endswith("JPG")==False \ and fileName_choose.endswith("png") == False \ and fileName_choose.endswith("PNG") == False: if filetype == "Bitmap Files (*.bmp)": fileName_choose = fileName_choose + ".bmp" elif filetype == "JPG (*.jpg)": fileName_choose = fileName_choose + ".jpg" elif filetype == "PNG (*.png)": fileName_choose = fileName_choose + ".png" else: fileName_choose = fileName_choose + ".bmp" ImageQt.fromqpixmap(self.my_canvas.pixmap()).save(fileName_choose) self.file_address = fileName_choose self.is_changed = 0
def save(self): #对参数的检查都在之前完成,假定此时参数都没错误 if (len(self.file_address) == 0): self.save_as() else: ImageQt.fromqpixmap(self.my_canvas.pixmap()).save( self.file_address) self.is_changed = 0
def open_image(self): """Открывает изображение, выбранное пользователем, вызывает функции для отображения миниатюр""" if not self.saved: flag = QMessageBox.question( self, '', 'Есть несохраненные изменения\nВы точно хотите продолжить?', QMessageBox.Yes, QMessageBox.No) if flag == QMessageBox.No: return self.filename = QFileDialog.getOpenFileName(self, 'Выберите изображение', '', 'Image (*.jpg *.png)')[0] if self.filename != '': self.menu_tab.setVisible(True) image = ImageQt.toqpixmap( self.normalize_image(Image.open(self.filename))) self.image_label.setText('') self.image_label.setPixmap(image) self.default_image = ImageQt.fromqpixmap(image) self.image = self.default_image.copy() self.set_default_values() self.set_filters_thumbnails(None) self.set_blurs_thumbnails(None) self.history_manager = HistoryHandler(self, self.filename) self.update_image()
def apply_effect(self, func): pixmap = self.img_label.pixmap image = ImageQt.fromqpixmap(pixmap) data = pic.to_arr(image) modifided_image = pic.to_img(func(data)) pixmap = ImageQt.toqpixmap(modifided_image) self.img_label.paint(pixmap)
def changeOutputColor(self): image = ImageQt.fromqpixmap(self.ui.label_image_output.pixmap()) image = image.resize((self.ui.label_image_output.size().width(), self.ui.label_image_output.size().height())) image_data = list(image.getdata()) newRGBA = (self.newR, self.newG, self.newB, self.rgba[3]) for index in self.changePos: image_data[index] = newRGBA image.putdata(image_data) if image.mode == "RGB": r, g, b = image.split() image = Image.merge("RGB", (b, g, r)) elif image.mode == "RGBA": r, g, b, a = image.split() image = Image.merge("RGBA", (b, g, r, a)) elif image.mode == "L": image = image.convert("RGBA") image2 = image.convert("RGBA") data = image2.tobytes("raw", "RGBA") qim = QImage(data, image.size[0], image.size[1], QImage.Format_ARGB32) pixmap = QPixmap.fromImage(qim) self.ui.label_image_output.setPixmap(QPixmap(pixmap))
def save_Webcam(self): if not os.path.exists('saved'): os.makedirs('saved') ISOTIMEFORMAT = '%Y-%m-%d-%H-%M-%S' theTime = datetime.datetime.now().strftime(ISOTIMEFORMAT) image = ImageQt.fromqpixmap(self.ui.graphicsView.pixmap()) image.save('./saved/' + theTime + '.jpg')
def get(self, pos): index = pos.y() * self.label_image_original.size().width() + pos.x() image = ImageQt.fromqpixmap(self.label_image_original.pixmap()) image = image.resize((self.label_image_original.size().width(), self.label_image_original.size().height())) image_data = image.getdata() self.rgba = image_data[index] if len(self.rgba) == 3: r, g, b = self.rgba elif len(image_data[index]) == 4: r, g, b, a = self.rgba self.changePos = [] index = 0 for item in image_data: if item == self.rgba: self.changePos.append(index) index += 1 print(len(self.changePos)) print(self.changePos) self.ui.label_color_original.setStyleSheet( 'background-color: rgb({},{},{});'.format(r, g, b)) self.ui.horizontalSlider_R.setDisabled(False) self.ui.horizontalSlider_G.setDisabled(False) self.ui.horizontalSlider_B.setDisabled(False)
def updateLabel(self, value): self.rotate_label.setText(str(value)) self.rotate_slider.setValue(value) image = ImageQt.fromqpixmap(self.label.original_image_pixmap) image = image.rotate(-1 * value) mask = self.label.original_mask_pixmap if mask: mask = ImageQt.fromqpixmap(mask) mask = mask.rotate(-1 * value) pixmap = self.label.merge_image_mask(image, mask) else: pixmap = ImageQt.toqpixmap(image) self.label.setPixmap(pixmap)
def del_channel(self, arr): pixmap = self.img_label.pixmap image = ImageQt.fromqpixmap(pixmap) data = pic.to_arr(image) modifided_image = pic.to_img(pic.del_channels(data, arr)) pixmap = ImageQt.toqpixmap(modifided_image) self.img_label.paint(pixmap)
def gen_hd_global_map_img(x=2000, y=2000, half_width=2020, use_all_data=True): global g_maxx, g_maxy, g_minx, g_miny, g_db_path get_db_path() print('g_db_path is:' + g_db_path) if not check_db_not_empty(): return ids = load_id_pos_from_db(x, y, half_width, use_all_data) if not ids: return time_start = datetime.now() width_max = 10240 height_max = 10240 canvas_width_param = g_maxx - g_minx + 2000 canvas_height_param = g_maxy - g_miny + 2000 if canvas_width_param > canvas_height_param: gv_width = width_max zoom_scale = float(width_max) / canvas_width_param gv_height = int(width_max * canvas_height_param / canvas_width_param) else: gv_height = height_max zoom_scale = float(height_max) / canvas_height_param gv_width = int(height_max * canvas_width_param / canvas_height_param) img_scale = max(int(IMG_LENGTH * zoom_scale * M2PRATIO), 1) gv_canvas = im.new('L', (gv_width, gv_height)) MAX_BATCH_SIZE=10000 batch_list = [ids[i:i+MAX_BATCH_SIZE] for i in range(0, len(ids), MAX_BATCH_SIZE)] i=0 for batch_ids in batch_list: i = i + 1 print("processing {}th batch data, batch size:{}".format(i, len(batch_ids))) all_pics_list = load_data_from_db_by_ids(batch_ids) #time_start1 = datetime.now() for itm in all_pics_list: img = imq.fromqpixmap(itm.img).convert('L').resize((img_scale, img_scale)) rot = itm.ot - PIXROTATE arr = np.array(img.convert('RGBA')) arr[:, :, 3] = (arr[:, :, 0] + arr[:, :, 1] + arr[:, :, 2] != 0) * arr[:, :, 3] gmi = im.fromarray(arr.astype('uint8')).rotate(rot, expand=True) shift = (gmi.size[0] - img_scale) // 2 pos_x = int(gv_width * ((itm.ox - shift) - g_minx + XGAP) / canvas_width_param) pos_y = int(gv_height * ((-1 * itm.oy + shift) - g_miny + YGAP) / canvas_height_param) gv_canvas.paste(gmi, (pos_x - img_scale // 2, gv_height - (pos_y - img_scale // 2)), gmi) # time_end1 = datetime.now() # print('paste pictures cost', time_end1-time_start1) dir_path = os.path.dirname(os.path.realpath(__file__)) + '/static/maps/' empty_dir(dir_path) time_str = time.strftime("%Y-%m-%d_%H-%M-%S",time.localtime(time.time())) pic_file_name = "hd_global_viewmap" + time_str + '.png' pic_path = dir_path + pic_file_name gv_canvas.save(pic_path) time_end = datetime.now() print('gen_hd_global_map_img() cost', time_end-time_start) relative_pic_path = 'static/maps/' + pic_file_name return relative_pic_path # for show
def open_file(self): file_path = QtWidgets.QFileDialog.getOpenFileName(self, 'Выберите файл с изображением' , filter="Images (*.png *.jpg *.jpeg *.bmp *.gif *.gif *.cur *.ico)")[0] if file_path: pixmap = QtGui.QPixmap.fromImage(QtGui.QImage(file_path)) self._original_image = ImageQt.fromqpixmap(pixmap) self._edited_image = self._original_image.copy() self.photo.setPixmap(pixmap) self.photo.resize(pixmap.width() , pixmap.height()) self.enable_elements() self.reset_values()
def mouseReleaseEvent(self, eventQMouseEvent): self.currentQRubberBand.hide() currentQRect = self.currentQRubberBand.geometry() self.currentQRubberBand.deleteLater() cropQPixmap = self.pixmap().copy(currentQRect) # cropQPixmap.save('output.png') crop_PIL = ImageQt.fromqpixmap(cropQPixmap) crop_PIL = pad_to_square(crop_PIL, self.target_size) cropQPixmap = ImageQt.toqpixmap(crop_PIL) self.setPixmap(cropQPixmap)
def on_capture(self): cam = VideoCapture(0) # 0 -> index of camera s, img = cam.read() if s: # frame captured without any errors namedWindow("camcapture") imshow("camcapture",img) waitKey(0) destroyWindow("camcapture") imwrite("capture.jpg",img) #save image logger.debug("capture") img_path = 'capture.jpg' if img_path: logger.debug(f"open file {img_path}") self.file_name = ntpath.basename(img_path) pix = QPixmap(img_path) self.img_lbl.setPixmap(pix) self.img_lbl.setScaledContents(False) self.action_tabs.setVisible(True) self.action_tabs.adjustment_tab.reset_sliders() global _img_original _img_original = ImageQt.fromqpixmap(pix) self.update_img_size_lbl() if _img_original.width < _img_original.height: w = THUMB_SIZE h = _get_ratio_height(_img_original.width, _img_original.height, w) else: h = THUMB_SIZE w = _get_ratio_width(_img_original.width, _img_original.height, h) img_filter_thumb = img_helper.resize(_img_original, w, h) global _img_preview _img_preview = _img_original.copy() for thumb in self.action_tabs.filters_tab.findChildren(QLabel): if thumb.name != "none": img_filter_preview = img_helper.color_filter(img_filter_thumb, thumb.name) else: img_filter_preview = img_filter_thumb preview_pix = ImageQt.toqpixmap(img_filter_preview) thumb.setPixmap(preview_pix) self.reset_btn.setEnabled(True) self.save_btn.setEnabled(True) self.action_tabs.modification_tab.set_boxes()
def on_upload(self, img_path): logger.debug("upload") if img_path: logger.debug("open file " + img_path) imageUri = QtCore.QUrl( QtCore.QString("file://{0}".format(img_path))) self.file_name = ntpath.basename(str(img_path)) pix = QPixmap(str(img_path)) self.img_lbl.setPixmap(pix) self.img_lbl.setScaledContents(True) self.action_tabs.setVisible(True) self.action_tabs.adjustment_tab.reset_sliders() global _img_original _img_original = ImageQt.fromqpixmap(pix) self.update_img_size_lbl() logger.debug("_img_original.width " + str(_img_original.width)) logger.debug("_img_original.height " + str(_img_original.height)) h = THUMB_SIZE w = THUMB_SIZE if _img_original.width < _img_original.height: w = THUMB_SIZE h = _get_ratio_height(_img_original.width, _img_original.height, w) elif _img_original.width > _img_original.height: h = THUMB_SIZE w = _get_ratio_width(_img_original.width, _img_original.height, h) img_filter_thumb = img_helper.resize(_img_original, w, h) global _img_preview _img_preview = _img_original.copy() for thumb in self.action_tabs.filters_tab.findChildren(QLabel): if thumb.name != "none": img_filter_preview = img_helper.color_filter( img_filter_thumb, thumb.name) else: img_filter_preview = img_filter_thumb preview_pix = ImageQt.toqpixmap(img_filter_preview) thumb.setPixmap(preview_pix) self.reset_btn.setEnabled(True) self.save_btn.setEnabled(True) self.action_tabs.modification_tab.set_boxes()
def on_upload(self): global img_path logger.debug("upload") img_path, _ = QFileDialog.getOpenFileName(self.parent, "Open image", "/Users", "Images (*.png *jpg)") if img_path: logger.debug(f"open file {img_path}") self.file_name = ntpath.basename(img_path) pix = QPixmap(img_path) self.img_lbl.setPixmap(pix) self.img_lbl.setScaledContents(True) self.action_tabs.setVisible(True) self.action_tabs.adjustment_tab.reset_sliders() global _img_original _img_original = ImageQt.fromqpixmap(pix) self.update_img_size_lbl() if _img_original.width < _img_original.height: w = THUMB_SIZE h = _get_ratio_height(_img_original.width, _img_original.height, w) else: h = THUMB_SIZE w = _get_ratio_width(_img_original.width, _img_original.height, h) img_filter_thumb = img_helper.resize(_img_original, w, h) global _img_preview _img_preview = _img_original.copy() for thumb in self.action_tabs.filters_tab.findChildren(QLabel): if thumb.name != "none": img_filter_preview = img_helper.color_filter( img_filter_thumb, thumb.name) else: img_filter_preview = img_filter_thumb preview_pix = ImageQt.toqpixmap(img_filter_preview) thumb.setPixmap(preview_pix) self.reset_btn.setEnabled(True) self.save_btn.setEnabled(True) self.action_tabs.modification_tab.set_boxes()
def mouseReleaseEvent(self, event): self.checkDraw() self.clearRect() self.img_cut = self.pixmap().copy(self.rect) self.setPixmap(self.img_cut) self.setAlignment(Qt.AlignCenter) # screen = QApplication.primaryScreen() # if screen is not None: # self.img_screen = screen.grabWindow(0, self.x0, self.y0, abs(self.x1-self.x0), abs(self.y1-self.y0)) # self.setPixmap(self.img_screen) # self.setScaledContents(False) img_pil = ImageQt.fromqpixmap(self.pixmap()) # qpixmap to image img_cv = cvtColor(asarray(img_pil), COLOR_RGB2BGR) # image to cv2 # 2 在需要的地方发射就行了 self.mouseReleased.emit([img_cv.mean()])
def merge_image_mask(self, image, mask): print(type(image), type(mask)) if type(image) == QPixmap and type(mask) == QPixmap: pil_image = ImageQt.fromqpixmap(image) pil_mask = ImageQt.fromqpixmap(mask) else: pil_image = image pil_mask = mask np_image = np.array(pil_image) np_mask = np.array(pil_mask) print(np_image.shape, np_mask.shape) prob = np.float32(np_mask) / 255.0 np_combo = np.uint8(np_image * (1 - prob) + np_mask * prob * np.array([[[0., 1., 0.]]])) pil_combo = Image.fromarray(np_combo) combo = ImageQt.toqpixmap(pil_combo) return combo
def BuscarImg(self): logger.debug("upload") img_path, _ = QFileDialog.getOpenFileName(self.parent, "Abrir imagem", "/Users", "Images (*.png *jpg)") if img_path: logger.debug(f"Abrir arquivo {img_path}") self.file_name = ntpath.basename(img_path) pix = QPixmap(img_path) self.img_lbl.setPixmap(pix) self.img_lbl.setScaledContents(True) self.action_tabs.setVisible(True) self.action_tabs.adjustment_tab.resetarDeslize() global _img_original _img_original = ImageQt.fromqpixmap(pix) self.AtualizarImg() if _img_original.width < _img_original.height: w = THUMB_SIZE h = _get_ratio_height(_img_original.width, _img_original.height, w) else: h = THUMB_SIZE w = _get_ratio_width(_img_original.width, _img_original.height, h) img_filter_thumb = ajustarImag.redimensionar(_img_original, w, h) global Vizualizar_Imag Vizualizar_Imag = _img_original.copy() for polegada in self.action_tabs.filters_tab.findChildren(QLabel): if polegada.name != "none": img_filter_preview = ajustarImag.cor_filtro(img_filter_thumb, polegada.name) else: img_filter_preview = img_filter_thumb preview_pix = ImageQt.toqpixmap(img_filter_preview) polegada.setPixmap(preview_pix) self.reset_btn.setEnabled(True) self.save_btn.setEnabled(True) self.action_tabs.modification_tab.caixaAjuste()
def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: self.isDrawing = False rect = QRect(self.startPoint, self.endPoint) self.result = self.screenshot.copy(rect) scan_result = zbar.decode(ImageQt.fromqpixmap(self.result)) self.fg.clearMask() self.hide() if len(scan_result) > 0: result_str = scan_result[0].data.decode() QApplication.clipboard().setText(result_str) QMessageBox.information(None, "结果", result_str + "\n内容已复制到剪贴板!") else: QMessageBox.warning(None, "错误", "没有发现二维码,请重试!")
def barcode_save(self): if self.code39.isChecked(): barcode_type = "Code39" else: barcode_type = "Code128" # file = QFileDialog(self.parent()).getSaveFileName( # self, "存放圖片位置", os.curdir, "PNG Files (*.png)") image = ImageQt.fromqpixmap(self.image.pixmap()) if barcode_type == 'Code39': filesave = filepath + "\\code39\\" + self.codeword.text() + ".png" print(filesave) image.save(filesave) elif barcode_type == 'Code128': filesave = filepath + "\\code128\\" + self.codeword.text() + ".png" image.save(filesave) self.alertmsg.setText('檔案存放到 ' + filesave)
def run(self): with graph.as_default(): image = ImageQt.fromqpixmap(self.pic) image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR) img = crop_faces(image) rgbImage = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) h, w, ch = rgbImage.shape bytesPerLine = ch * w convertToQtFormat = QImage(rgbImage.data, w, h, bytesPerLine, QImage.Format_RGB888) self.normalized_pic.emit(convertToQtFormat) img = Image.fromarray(rgbImage) img = img.resize((299, 299)) x = np.expand_dims(img, axis=0) x = x * 1. / 255 X = model.predict_classes(x) self.bmi.emit(str(Label[X[0]]))
def _filter(self): image = ImageQt.fromqpixmap(self.img) # image = ImageEnhance.Brightness(image) # image = image.enhance(self.brightness_v) v = int(self.brightness_v * 10) if v != 0: image = np.array(image, dtype=int) image += v image = np.clip(image, 0, 255) image = Image.fromarray(np.uint8(image)) if self.angle_v != 0: image = image.transpose(getattr(Image, "ROTATE_{}".format(self.angle_v))) scaled_img = ImageQt.toqpixmap(image) if self.angle_v == 90 or self.angle_v == 270: scaled_img = scaled_img.scaled(int(self.img.height() * self.ratio), int(self.img.width() * self.ratio)) else: scaled_img = scaled_img.scaled(int(self.img.width() * self.ratio), int(self.img.height() * self.ratio)) return scaled_img
def slot_btn_save(self): if not self.image: QMessageBox.critical(self, '错误', '没有加载图片', QMessageBox.Yes) return try: save_path, ok = QFileDialog.getSaveFileName(self, '选择文件夹', filter='*.jpg') if not ok: return save_image = ImageQt.fromqpixmap(self.disPicture.pixmap()) if not save_image: QMessageBox.critical(self, '错误', '没有加载图片!', QMessageBox.Yes) return print(save_path) save_image.save(save_path, quality=90) except: QMessageBox.critical(self, '错误', '保存文件失败!', QMessageBox.Yes) print('error while saving image!') return QMessageBox.information(self, 'YOLO系统', '保存成功!', QMessageBox.Yes)
def saveEvent(self): image1 = ImageQt.fromqpixmap(self.ui.label.pixmap()) image2 = ImageQt.fromqimage(self.pLabel.grab()) image1 = image1.convert('RGBA') image2 = image2.resize(image1.size) # Transparency newImage2 = [] for item in image2.getdata(): if item[:3] == (240, 240, 240): newImage2.append((240, 240, 240, 0)) else: newImage2.append(item) image2.putdata(newImage2) print(image1.mode, image1.size) print(image2.mode, image2.size) newImage = Image.alpha_composite(image1, image2) newImage.save('test.png')
def load_image(self, img_path): self.viewer.setPhoto(QtGui.QPixmap(img_path)) self._empty = False logger.debug(f"open file {img_path}") self.name = img_path print(self.name) global _img_path _img_path = self.name pix = QPixmap(img_path) self.action_tabs.setVisible(True) self.action_tabs.adjustment_tab.reset_sliders() self.action_tabs.histogram_tab.reset_sliders() global _img_original _img_original = ImageQt.fromqpixmap(pix) if _img_original.width < _img_original.height: w = THUMB_SIZE h = _get_ratio_height(_img_original.width, _img_original.height, w) else: h = THUMB_SIZE w = _get_ratio_width(_img_original.width, _img_original.height, h) img_filter_thumb = img_helper.resize(_img_original, w, h) global _img_preview _img_preview = _img_original.copy() for thumb in self.action_tabs.filters_tab.findChildren(QLabel): if thumb.name != "none": img_filter_preview = img_helper.color_filter( img_filter_thumb, thumb.name) else: img_filter_preview = img_filter_thumb preview_pix = ImageQt.toqpixmap(img_filter_preview) thumb.setPixmap(preview_pix) self.action_tabs.modification_tab.set_boxes()
def direction_btn_press(self, forward=True): folder = self.outDirLine.text() fname = self.images_list[self.idx] fname = os.path.basename(fname) fname = fname.split('.')[0] + '.png' image = ImageQt.fromqpixmap(self.label.pixmap()) image.save(os.path.join(folder, fname)) if forward: self.idx += 1 else: self.idx -= 1 if self.idx < 0: self.idx = 0 elif self.idx > len(self.images_list) - 1: self.idx = self.idx - 1 self.rotate_slider.valueChanged.emit(0) self.read_pad_show(self.images_list[self.idx]) self.cur_pos_label.setText(f'Position: {self.idx + 1}')
def saveEvent(self): image = ImageQt.fromqpixmap(self.ui.label_image_output.pixmap()) image.save('test.png')
def savePhoto(self): global fsplit image = ImageQt.fromqpixmap(self.ui.label.pixmap()) image.save('./outputs/Snap/'+fsplit+'.png')
def roundtrip(self, expected): PillowQtTestCase.setUp(self) result = ImageQt.fromqpixmap(ImageQt.toqpixmap(expected)) # Qt saves all pixmaps as rgb self.assert_image_equal(result, expected.convert('RGB'))
def roundtrip(expected): result = ImageQt.fromqpixmap(ImageQt.toqpixmap(expected)) # Qt saves all pixmaps as rgb assert_image_equal(result, expected.convert("RGB"))
def pixmap2pil(self, pixmap): # print("QPixmap格式转PIL格式") return ImageQt.fromqpixmap(pixmap)