def watermark_file(input_file, output_file, text, font_file, **kwargs): original = Image.open(input_file) # Обработка параметров quality = kwargs.pop("quality") compress = kwargs.pop("compress") resize = kwargs.pop("resize") if original.format == TIFF: with TiffImagePlugin.AppendingTiffWriter(output_file, True) as tif: for i in range(original.n_frames): original.seek(i) out = watermark_image(original, text, font_file, **kwargs) compression = "jpeg" if compress else "None" if resize: xs, ys = out.size ratio = resize / xs out.thumbnail((xs * ratio, ys * ratio), Image.ANTIALIAS) out.save(tif, compression=compression, quality=quality) tif.newFrame() elif original.format in (PNG, JPG, JPEG): out = watermark_image(original, text, font_file, **kwargs) out.save(output_file, quality=quality) else: raise UnsupportedFileExtension( "Format {0} not supported".format(original.format))
def diff_png(p2modded, p2original, relative, out): # open original and mod original = Image.open(p2original) mod = Image.open(p2modded) LOG.info("Original {} is mode={}, width={}, height={}".format(p2original, original.mode, original.width, original.height)) LOG.info("Modded {} is mode={}, width={}, height={}".format(p2modded, mod.mode, mod.width, mod.height)) # create a 1bit mask out of differences, converting grayscale in 0/1 diff = ImageChops.difference(mod, original) mask = diff.convert(mode="L").point( lambda x: 0 if x==0 else 1, mode="1") # create final mod reduced to mask masked_mod = Image.composite(mod, Image.new(mod.mode, mod.size), mask) masked_mod.putalpha(mask) masked_original = Image.composite(original, Image.new(original.mode, original.size), mask) masked_original.putalpha(mask) # prepare meta information of original relative path ifd = TiffImagePlugin.ImageFileDirectory_v2() ifd[269] = relative ifd.tagtype[269] = TiffImagePlugin.TiffTags.ASCII with TiffImagePlugin.AppendingTiffWriter(out+".tiff",True) as tf: masked_original.save(tf, compression="tiff_deflate", tiffinfo=ifd) tf.newFrame() masked_mod.save(tf, compression="tiff_deflate", tiffinfo=ifd)
def open_tiff_play(image_path, box_path, output_path, draw_boxes=False): img = Image.open(image_path, mode='r') # Initialize filter with TiffImagePlugin.AppendingTiffWriter(output_path, True) as tf: with open(box_path, 'r') as bf: findex = 0 box_text = None new_page = False while True: try: img.seek(findex) except Exception: break frame = img # ipdb.set_trace() # TODO Add noise here add_pepper_noise(frame, row_freq=1, points_each_row_fraction=0.1) # Draw bounding boxes if draw_boxes: rec_draw = ImageDraw.Draw(frame) while True: if not (box_text and new_page): box_text = bf.readline().split('\n')[0] if not box_text: break if new_page: new_page = False box_info = box_text.split(' ') page = int(box_info[-1]) if page > findex: new_page = True break if len(box_info) == 6 and box_info[0] != '\t': xmin = int(box_info[1]) ymin = frame.height - int(box_info[2]) xmax = int(box_info[3]) ymax = frame.height - int(box_info[4]) elif len(box_info) == 7: xmin = int(box_info[2]) ymin = frame.height - int(box_info[3]) xmax = int(box_info[4]) ymax = frame.height - int(box_info[5]) rec_draw.rectangle([xmin, ymin, xmax, ymax]) frame.save(tf) tf.newFrame() findex += 1
def convert_to_multipage_tiffs(merged_file_name): with TiffImagePlugin.AppendingTiffWriter(merged_file_name,True) as tf: for tiff_in in file_list: try: im= Image.open(tiff_in) im.save(tf) tf.newFrame() im.close() print(tiff_in) except: print('Error')
def test(): for count in tqdm(range(len(test_images))): im = test_images[count] im = np.reshape(im, (1, im.shape[0], im.shape[1], 1)) out = sim_gan.refiner.predict(im) # refine a single simulated image print(out) refined_image = MAX_VAL * np.squeeze( (out + 1) / 2.) # shift output image from [-1, 1] to [0, MAX_VAL] print(np.max(refined_image)) simulated_image = np.squeeze(im) simulated = Image.fromarray(simulated_image.astype(np.uint16)) refined = Image.fromarray(refined_image.astype(np.uint16)) with TiffImagePlugin.AppendingTiffWriter(simulated_path) as stf: simulated.save(stf) stf.newFrame() with TiffImagePlugin.AppendingTiffWriter(refined_path) as rtf: refined.save(rtf) rtf.newFrame()
def scanwrite(self, feed, filename, client_notify): logging.info("creating {}".format(filename)) pages=[] with TiffImagePlugin.AppendingTiffWriter(filename,new=True) as tiff: for i,page in enumerate(feed): logging.info('saving page {}...'.format(i+1)) client_notify("PAGE {}".format(i+1)) page.save(tiff,dpi=(feed.dev.resolution,feed.dev.resolution)) tiff.newFrame() pages.append(page) logging.debug("saved") subprocess.run(["convert","-compress","zip",filename,filename]) return pages
def convert_pdf_to_tiff(self, filename, delete_original=False): self.open_pdf(filename) i = 0 list_file = [] basefile = os.path.basename(filename) title = os.path.splitext(basefile)[0] new_files = [] while i < self.PAGE_COUNT: pages = convert_from_path(filename, 200) # Save Cover Sheet as Separate File if i == 0: new_filename = f"{title}-coversheet.tif" pages[i].save(new_filename, "TIFF", compression="jpeg") new_files.append(new_filename) else: # Handle remaining pages tempfile = f"temp_{title}-{i}.tif" list_file.append(tempfile) pages[i].save(tempfile, "TIFF", compression="jpeg") i += 1 pages.clear() if self.PAGE_COUNT > 1: new_filename = f"{title}.tif" with TiffImagePlugin.AppendingTiffWriter(new_filename, True) as tf: for tiff_in in list_file: try: im = Image.open(tiff_in) im.save(tf) tf.newFrame() im.close() finally: os.remove(tiff_in) # delete temp file pass new_files.append(new_filename) print("Conversion complete!") if delete_original: print("Removing original PDF...") os.remove(filename) print("Local PDF deleted!") return new_files
def correct(image, type, coef): with open(image, 'rb') as img_file: tags = exif.process_file(img_file, strict=False, details=False) exposure = tags["EXIF ExposureTime"].values[0].num / float( tags["EXIF ExposureTime"].values[0].den) gain = tags["EXIF ISOSpeedRatings"].values[0] / 100.0 print("{} : Exp: {} Gain: {}".format(image, exposure, gain)) normalization = 1.0 / (exposure * gain) original = Image.open(img_file) img = np.float32(original) width = img.shape[0] height = img.shape[1] depth = img.shape[2] # Apply color correction by reshaping, multiplying, and undoing the reshape img_corr = np.reshape(img, (width * height, depth)) np.dot(img_corr, coef, img_corr) img_corr = np.reshape(img_corr, (width, height, depth)) # Apply exposure normalization img_corr *= normalization print("Corr Max/Avg: {} / {}".format(np.amax(img_corr, (0, 1)), np.average(img_corr, (0, 1)))) images = [ Image.fromarray(img_corr[:, :, RED]), Image.fromarray(img_corr[:, :, GRN]), Image.fromarray(img_corr[:, :, BLU]), ] with TiffImagePlugin.AppendingTiffWriter(image + "." + type + ".corr.tiff", True) as tf: for tiff in images: tiff.save(tf) tf.newFrame()
def make_tif_play(): text = 'おはようございます。\n' \ 'こんにちは。\n' \ 'ご誕生日おめでとうございます。' font = 'TextRecognitionDataGenerator/fonts/jp/TakaoGothic.ttf' text_color = (255, 0, 0) image_font = ImageFont.truetype(font=font, size=12, index=0) text_width, text_height = image_font.getsize(text) txt_img = Image.new('RGB', (text_width, text_height * 3), (0, 255, 0)) txt_draw = ImageDraw.Draw(txt_img) txt_draw.text((0, 0), text, fill=text_color, font=image_font) with TiffImagePlugin.AppendingTiffWriter('./test.tif', True) as tf: txt_img = txt_img.convert('1') txt_img.save(tf) tf.newFrame() ipdb.set_trace() imgcp = Image.open('./test.tif')
def makeReaderFile(self, event): # sel = self.rb.GetSelection() # print("RadioBox selection", sel) # n = self.textExistingFile.GetNumberOfLines() # print("Lines", n) existingFileName = self.textExistingFile.GetValue() if existingFileName == "": print("no file to work on") ck_file = Path(existingFileName) if not ck_file.is_file(): wx.MessageBox(message="Input file does not exist, or is not valid", caption='Bad file', style=wx.OK | wx.ICON_INFORMATION) return filename, file_extension = os.path.splitext(existingFileName) # filename, unused if file_extension != '.tif': wx.MessageBox(message="Input file must be 'tif' format", caption='Bad file', style=wx.OK | wx.ICON_INFORMATION) return print("existingFileName:", existingFileName) newCopyFileName = self.textNewFileName.GetValue() if newCopyFileName == "": print("no new file to create") filename, file_extension = os.path.splitext(newCopyFileName) if file_extension != '.tif': wx.MessageBox(message="New copy file must be 'tif' format", caption='Bad file', style=wx.OK | wx.ICON_INFORMATION) return print("newFileName:", newCopyFileName) sel = self.rb.GetSelection() if sel == 0: print("Normal, page tops are to left of sheets") even_page = 1 # first page is an even page rotationAngle = -90 else: print("Reversed, page tops are to right of sheets") even_page = -1 # first page is an odd page rotationAngle = 90 fp = existingFileName try: im_all = Image.open(fp) except IOError as e: print("Unable to open input file") wx.MessageBox(message="Can't open input file", caption='Bad file', style=wx.OK | wx.ICON_INFORMATION) return newfile = newCopyFileName try: tf = TiffImagePlugin.AppendingTiffWriter(newfile, True) except IOError as e: print("Unable to create output file") wx.MessageBox(message="Can't create output file", caption='Bad file', style=wx.OK | wx.ICON_INFORMATION) return # num_orig_pages = im_all.n_frames # orig_dpi = im_all.info['dpi'] # print("number of pages to parse", num_orig_pages) # num_output_pages = num_orig_pages * 2 stored_imgs = [] for i, page in enumerate(ImageSequence.Iterator(im_all)): pgwidth, pgheight = page.size pgdpi = page.info['dpi'] print("parsing page", i) halfheight = pgheight / 2 topbox = (0, 0, pgwidth, halfheight) bottombox = (0, halfheight, pgwidth, pgheight) im_bottom = page.crop(bottombox).rotate(rotationAngle, 0, 1) im_top = page.crop(topbox).rotate(rotationAngle, 0, 1) # add the top if an even page, the bottom if an odd page # store the other half if even_page > 0: im_save = im_top im_store = im_bottom else: im_save = im_bottom im_store = im_top ## # temporary diagnostics, to check pixel ranges ## if i == 0: # save the pages from the first sheet ## file_pth, file_ext = os.path.splitext(newCopyFileName) ## im_ck = copy.copy(page) ## im_ck.save(file_pth + "_ck_sheet" + file_ext) ## im_bottom.save(file_pth + "_ck_bottom" + file_ext) ## im_top.save(file_pth + "_ck_top" + file_ext) print("image", i, ", stored DPI", pgdpi) saveFrameToTIFBeingBuilt(im_save, tf, pgdpi) stored_imgs.append((copy.copy(im_store), copy.copy(pgdpi))) even_page = -even_page #toggle even/odd # done with the orginal file im_all.close() # now insert the stored pages print("inserting stored half-pages") stored_imgs.reverse() for im in stored_imgs: print("image, stored DPI", im[1]) saveFrameToTIFBeingBuilt(im[0], tf, im[1]) tf.close() print("done") wx.MessageBox(message="Done", caption='Done', style=wx.OK | wx.ICON_INFORMATION)
for tif_file in tif_files: # file_name_without_extension = os.path.basename(tif_file).replace('.tif', '') file_path_without_extension = tif_file.replace('.tif', '') box_file = file_path_without_extension + '.box' tif_img = Image.open(tif_file, mode='r') for pepper_noise_setting in pepper_noise_settings: # Copy box file out_box_file = file_path_without_extension + '_pepper-{}-{}.box'.format( pepper_noise_setting[0], pepper_noise_setting[1]) shutil.copyfile(box_file, out_box_file) # Make new .tif file with noise out_tif_file = file_path_without_extension + '_pepper-{}-{}.tif'.format( pepper_noise_setting[0], pepper_noise_setting[1]) with TiffImagePlugin.AppendingTiffWriter(out_tif_file, True) as tf: findex = 0 while True: try: tif_img.seek(findex) except Exception: break frame = tif_img.copy() # Add noise add_pepper_noise( frame, row_freq=pepper_noise_setting[0], points_each_row_fraction=pepper_noise_setting[1]) frame.save(tf)