def _create_proxy_rawpy(self, source, dest, mode): # maybe Pillow supports this file type directly? if not self.image: try: self.image = Image.open(source) except IOError: pass except Exception as e: logging.error('cannot read {}: {}'.format(source, e.args[0])) raise e # obviously not, try decoding as Raw if not self.image: try: raw = rawpy.imread(source) rgb = raw.postprocess(use_camera_wb=True, no_auto_bright=True) self.image = Image.fromarray(rgb) except Exception as e: logging.error('cannot read {}: {}'.format(source, e.args[0])) raise e image = self.image.copy() if mode == self.PROXY_FULLSIZE: pass elif mode == self.PROXY_THUMBNAIL: image.thumbnail(settings.THUMBNAILSIZE) elif mode == self.PROXY_WEBSIZED: image.thumbnail(settings.WEBSIZE) try: image.save(dest) except Exception as e: logging.error('cannot write {}: {}'.format(dest, e.args[0]))
def new_blank_png(width, height, color=None): if color: new_img = Image(width=width, height=height, background=color) else: new_img = Image(width=width, height=height) return new_img.convert('png')
def pdf_to_text(filename): pdf = IM(filename=filename, resolution=300) pages = len(pdf.sequence) image = IM(width=pdf.width, height=pdf.height * pages) for i in xrange(pages): image.composite( pdf.sequence[i], top=pdf.height * i, left=0 ) img = image.convert('png') with tempfile.NamedTemporaryFile(prefix="tess_") as temp_file: img.save(filename=temp_file.name) try: temp = tempfile.NamedTemporaryFile(delete=False) process = subprocess.Popen(['tesseract', temp_file.name, temp.name], \ stdout=subprocess.PIPE, stderr=subprocess.STDOUT) process.communicate() with open(temp.name + '.txt', 'r') as handle: contents = handle.read() os.remove(temp.name + '.txt') os.remove(temp.name) print contents except: print "ERROR"
def pdf2text(pdf_filename): tool = pyocr.get_available_tools()[0] lang = tool.get_available_languages()[1] req_image = [] final_text = [] image_pdf = Image(filename=pdf_filename, resolution=300) image_jpeg = image_pdf.convert('jpeg') for img in image_jpeg.sequence: img_page = Image(image=img) req_image.append(img_page.make_blob('jpeg')) for img in req_image: txt = tool.image_to_string( PI.open(io.BytesIO(img)), lang=lang, builder=pyocr.builders.TextBuilder() ) final_text.append(txt) return final_text
def _pdf_thumbnail(filename): img = WandImage(filename=filename + '[0]') img.background_color = Color('white') tw, th = get_thumbnail_size(img.height, img.width, 50, 50) img.resize(tw, th) rawData = img.make_blob('jpeg') return base64.b64encode(rawData)
def process(self): image = Image( filename='%s/%s' % (self.upload_path, self.record.filename) ) ratio = float(image.width) / float(image.height) height = image.height width = image.width if image.height > 300: height = 300 width = int(300.0 * ratio) if width > 700: width = 700 height = int(700.0 / ratio) self.record.extra = json.dumps({ 'height': image.height, 'width': image.width, 'thumb': { 'height': width, 'width': height, }, }) image.resize(width, height) image.save(filename=self.thumbnail_file)
def convert(self, PDFname): p = Image(file = PDFname, format = 'png') p = p.sequence[0] p = Image(p) p.resize(50, 50) #p.save(filename = "test.png") #This line is for demos return p
def main(argv): input_file_spec = '' output_file_path = '' if len(argv) != 3: print 'usage: proeprocess_images.py <input_file_spec> <output_path>' sys.exit(-1) input_file_spec = argv[1] output_file_path = argv[2] file_number = 1 file_path = input_file_spec % file_number while os.path.exists(file_path): output_root_file = os.path.splitext(os.path.basename(file_path))[0] output_path = os.path.join(output_file_path, output_root_file + '.tiff') print 'processing %s to %s' % (file_path, output_path) img = Image(filename=file_path) # remove any letterboxing from top and bottom, unfortunately this eats other # elements too which can end up interfering negatively with cropping # trimmer = img.clone() # trimmer.trim() # if trimmer.size[0] > 1: # img = trimmer # img.reset_coords() # resize to 180px tall at original aspect ratio original_size = img.size scale = 192.0 / float(original_size[1]) scale_width = int(scale * float(original_size[0])) # always make even width for centering, etc. # if scale_width % 2 == 1: # scale_width -= 1 img.resize(width=scale_width, height=192) img.save(filename=output_path) file_number += 1 file_path = input_file_spec % file_number
def wand1(): """This is Python Wand example 1""" the_time = t.asctime() print "Importing image ", IFILE img_1 = Image(filename=IFILE) print "Cropping and resizing the image" img_1.crop(300, 0, width=300, height=282) img_1.resize(width=600, height=564) print "Creating a drawing and overlaying on it" draw = Drawing() draw.circle((100, 100), (120, 120)) draw.rectangle(left=img_1.width-300, top=img_1.height-45, width=230, height=40, radius=5) draw.font_size = 17 draw.fill_color = Color('white') draw.text_color = Color('white') draw.text(img_1.width-290, img_1.height-20, the_time) draw(img_1) print "Displaying, close the XTERM when done" display(img_1)
def _create_image(self, image_argument): image = None if isinstance(image_argument, Image): image = image_argument if isinstance(image_argument, (str, unicode)): image_file = urllib.urlopen(image_argument) image = Image(blob=image_file.read()) elif isinstance(image_argument, dict): config = image_argument if 'raw_image' not in config: raise KeyError("Should have image in config") if not isinstance(config['raw_image'], Image): raise TypeError("config['raw_image'] should be Image") image = config['raw_image'] transforms = config.get('transforms', []) for t in transforms: image.transform(**t) if image is None: raise ValueError("Generate Fail") return image
def pdf2ocr(pdffile): """ Optical Character Recognition on PDF files using Python see https://pythontips.com/2016/02/25/ocr-on-pdf-files-using-python/ :param pdffile: pdffile to be OCR'd :return: """ from wand.image import Image from PIL import Image as PI import pyocr import pyocr.builders import io tool = pyocr.get_available_tools()[0] lang = tool.get_available_languages()[0] # [0] for english req_image = [] final_text = [] print "Reading {0}".format(pdffile) image_pdf = Image(filename=pdffile, resolution=300) image_jpeg = image_pdf.convert("jpeg") for img in image_jpeg.sequence: img_page = Image(image=img) print ("appending image") req_image.append(img_page.make_blob("jpeg")) print "Generating text" for img in req_image: txt = tool.image_to_string(PI.open(io.BytesIO(img)), lang=lang, builder=pyocr.builders.TextBuilder()) final_text.append(txt) return final_text
def create_thumb(self, img_path, date, text): img = Image(filename=os.path.join(self.source_dir, img_path)) img.resize(self.thumb_size, self.thumb_size) pixmap_on = QtGui.QPixmap() pixmap_on.loadFromData(img.make_blob()) with Drawing() as draw: draw.stroke_color = Color('white') draw.stroke_width = 3 draw.line((0, 0), (self.thumb_size, self.thumb_size)) draw.line((0, self.thumb_size), (self.thumb_size , 0)) draw(img) pixmap_off = QtGui.QPixmap() pixmap_off.loadFromData(img.make_blob()) btn = IconButton(pixmap_on, pixmap_off, img_path, date, text) btn.clicked.connect(self.thumb_clicked) size = pixmap_on.size() w, h = size.toTuple() btn.setIconSize(size) btn.setFixedSize(w+20, h+20) self.scroll_vbox.addWidget(btn)
def create_thumb(size, blob): '''Creates proportionally scaled thumbnail and save to destination. Returns thumbnaill location and source mimetype''' mimetype = None with Image(blob=blob) as source: image = Image(source.sequence[0]) if source.sequence else source mimetype = image.mimetype if mimetype == None: raise InvalidImageException('Invalid image mimetype!') w, h = image.size if w > size[0]: h = int(max(h * size[0] / w, 1)) w = int(size[0]) if h > size[1]: w = int(max(w * size[1] / h, 1)) h = int(size[1]) size = w, h if size == image.size: #image.save(filename=destination + '.' + extension) return image, mimetype image.sample(*size) #image.save(filename=destination + '.' + extension) return image, mimetype
def generate_square_img(self, img_path, size_config, size_img, size_name, dest_path): #open_image img = Image(filename=img_path) #transform with resize scale config img.transform(resize=size_config) #try to crop, calculate width crop first target_size = size_img[1] #use one because its square width, height = img.size #print "width, height ", width, height crop_start, crop_end = [0, 0] #add new size params #calculate crop_start = (width - target_size) / 2 crop_end = crop_start + target_size #print crop_start, crop_end, target_size, (crop_end - crop_start) ''' exProcessor = ExifData() #rotate image if necessary if exProcessor.check_orientation(img) in [6, 7]: img.rotate(90) img.metadata['exif:Orientation'] = 1 if exProcessor.check_orientation(img) in [6, 8]: img.rotate(-90) img.metadata['exif:Orientation'] = 1 if exProcessor.check_orientation(img) in [3, 4]: img.rotate(180) img.metadata['exif:Orientation'] = 1 ''' #do cropping with img[crop_start:crop_end, :] as square_image: #save square_image.save(filename=''.join([dest_path, size_name, '.jpg']))
def convert_pdf_to_img(blob, img_type="jpg", quality=75, resolution=200): """ Converts PDF with multiple pages into one image. It needs the file content NOT the filename or ioBytes and returns the image content. Note: It has memory leak!! http://stackoverflow.com/a/26233785/1497443 Example: with open('my.pdf', "r") as f: file_content = f.read() # import ipdb # ipdb.set_trace() hh = convert_pdf_to_jpg(file_content) with open('my.jpg', 'wb') as f: f.write(hh) """ from wand.image import Image as WandImage from wand.color import Color as WandColor pdf = WandImage(blob=blob, resolution=resolution) pages = len(pdf.sequence) wimage = WandImage(width=pdf.width, height=pdf.height * pages, background=WandColor("white")) for i in xrange(pages): wimage.composite(pdf.sequence[i], top=pdf.height * i, left=0) if img_type == "jpg": wimage.compression_quality = quality return wimage.make_blob(img_type)
def do_polaroid (image, filename=None, background="black", suffix=None): if suffix is None: suffix = PARAMS["IMG_FORMAT_SUFFIX"] tmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix) tmp.close() print("Saving image into {}...".format(tmp.name)) image.save(filename=tmp.name) print("Done") if not(PARAMS["WANT_NO_CAPTION"]) and filename: details = get_file_details(filename) caption = """-caption "%s" """ % details.replace("'", "\\'") else: caption = "" command = ("convert " "-bordercolor snow "+ "-background %(bg)s "+ "-gravity center %(caption)s "+ "+polaroid %(name)s %(name)s") % {"bg" : background, "name":tmp.name, "caption":caption} ret = subprocess.call(command, shell=True) if ret != 0: raise Exception("Command failed: "+ command) img = Image(filename=tmp.name).clone() os.unlink(tmp.name) img.resize(width=image.width, height=image.height) return img
def scale(imagePath, face): # cloneImg.save(filename='{0}-{1}.jpg'.format(imagePath, i)) face_x, face_y, face_w, face_h = face with Image(filename=imagePath) as img: img_w = img.size[0] img_h = img.size[1] w_delta = ((img_w - face_w) / 2) / NUM_IMAGES h_delta = ((img_h - face_h) / 2) / NUM_IMAGES gifImg = Image() for i in range(NUM_IMAGES, -1, -1): with img.clone() as cloneImg: if i == 0: cloneImg.crop(face_x, face_y, width=face_w, height=face_h) cloneImg.transform(resize='%dx%d' % (img_w, img_h)) else: left = max(0, face_x - i * w_delta) top = max(0, face_y - i * h_delta) right = min(img_w, face_x + face_w + i * w_delta) bottom = min(img_h, face_y + face_h + i * h_delta) cloneImg.crop(left, top, right, bottom) cloneImg.transform(resize='%dx%d' % (img_w, img_h)) gifImg.sequence.append(cloneImg) for frame in gifImg.sequence: with frame: frame.delay = 20 gifImg.save(filename='%s.gif' % imagePath) gifImg.close() return '%s.gif' % imagePath
def pdf2img(pdf_path): print "Converting pdf section to image..." img = Image(filename=pdf_path) imgname=pdf_path[:pdf_path.rindex('.')]+ext print "Saving image: "+imgname[imgname.rindex('\\')+1:] img.save(filename=imgname) return imgname
def main(): funky_img = Image(filename="../images/funky_illustration.png") funky_img = resize_to_percent(funky_img, 60) cropped_img = funky_img.clone() cropped_img.crop(top=0, left=275, width=340, height=486) display(funky_img) display(cropped_img)
def pdf_preview(tmp_file_path, tmp_dir): if use_generic_pdf_cover: return None else: if use_PIL: try: input1 = PdfFileReader(open(tmp_file_path, 'rb'), strict=False) page0 = input1.getPage(0) xObject = page0['/Resources']['/XObject'].getObject() for obj in xObject: if xObject[obj]['/Subtype'] == '/Image': size = (xObject[obj]['/Width'], xObject[obj]['/Height']) data = xObject[obj]._data # xObject[obj].getData() if xObject[obj]['/ColorSpace'] == '/DeviceRGB': mode = "RGB" else: mode = "P" if '/Filter' in xObject[obj]: if xObject[obj]['/Filter'] == '/FlateDecode': img = Image.frombytes(mode, size, data) cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.png" img.save(filename=os.path.join(tmp_dir, cover_file_name)) return cover_file_name # img.save(obj[1:] + ".png") elif xObject[obj]['/Filter'] == '/DCTDecode': cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.jpg" img = open(cover_file_name, "wb") img.write(data) img.close() return cover_file_name elif xObject[obj]['/Filter'] == '/JPXDecode': cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.jp2" img = open(cover_file_name, "wb") img.write(data) img.close() return cover_file_name else: img = Image.frombytes(mode, size, data) cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.png" img.save(filename=os.path.join(tmp_dir, cover_file_name)) return cover_file_name except Exception as ex: print(ex) try: cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.jpg" with Image(filename=tmp_file_path + "[0]", resolution=150) as img: img.compression_quality = 88 img.save(filename=os.path.join(tmp_dir, cover_file_name)) return cover_file_name except PolicyError as ex: logger.warning('Pdf extraction forbidden by Imagemagick policy: %s', ex) return None except Exception as ex: logger.warning('Cannot extract cover image, using default: %s', ex) return None
def clone_downscale_save(input_file, output_file, pixels=3000000, width=None, height=None, compression_quality=92): orig = Image(filename=input_file) img = orig.clone() img = downscale(img, pixels, width, height, compression_quality) # Make sure output directory exists dirname, _basename = os.path.split(output_file) mkdir_p(dirname) # Noop if dir already exists img.save(filename=output_def)
def process_pattern(raw_content): img = Image(file=StringIO(raw_content)) base_img = img.convert('tiff') flag = False if img.type in ['bilevel', 'grayscale', 'grayscalematte']: flag = True base = StringIO() base_img.save(file=base) base.seek(0) return base, flag
def cache_blob(self, blob_data, checkout_id, filename): """ Write a blob of data to disk according to the specified checkout id and filename. """ thumbs_dir = "cookbook/assets/img/thumbnails" new_img = Image(blob=blob_data) thumb_file = "%s/%s_%s" % (thumbs_dir, checkout_id, filename) log.info("save thumbnail to: %s", thumb_file) new_img.save(filename=thumb_file)
def series_to_animated_gif(L, filepath): imgs = Image(filename=L[0]) for i in L[1:]: im2 = Image(filename=i) imgs.sequence.append(im2) for i in imgs.sequence: i.delay = 25 imgs.save(filename=filepath) imgs.close() print('saved animated.gif')
def pdf2img(pdf_path): #print "entered pdf2img" #print "CONVERTING SCALED PDF TO AN IMAGE" #print "---------------------------------------------------" img = Image(filename=pdf_path) imgname=pdf_path[:pdf_path.rindex('.')]+ext #print "SAVING CONVERTED IMAGE AS: "+imgname[imgname.rindex('/')+1:] #print "---------------------------------------------------" img.save(filename=imgname) return imgname
def test_ico_masquerading_as_jpg_big(self, s3): obj = mock.Mock() image = Image(width=16, height=16) obj.content = image.make_blob('ico') obj.headers = {'content-type': 'image/jpeg'} # this is what S3 tells us =( s3.get.side_effect = [obj, make_httperror(404)] r = self.app.get("/{}/giant.jpg?w=400&h=400".format(self.bucket)) self.assertEqual(r.status_code, 200) content_type = r.headers.get("content-type") self.assertEqual(content_type, "image/jpeg") self.assertEqual(Image(blob=r.data, format='jpeg').size, (400, 400))
def save(self, *args, **kwargs): super(UploadComics, self).save() img = Image(filename=self.pdf._get_path(), resolution=200) img.save(filename=settings.BASE_DIR + '/static_in_env/media_root/images/temp-%s-%s.jpg' % ( self.id, self.name)) comic = Comics.objects.create(general_id=self.id) for i in range(len(img.sequence)): image = ComicsImage(image='/media/images/temp-%s-%s-%s.jpg' % (self.id, self.name, i)) image.save() comic.pages.add(image) comic.save()
def pdf2image(self,dest_width, dest_height): RESOLUTION = 300 #blob = self.datas.decode('base64') #raise Warning(self.base64_decode(self.datas)) #str = self.datas + '=' *(-len(self.datas)%4) #img = Image(blob=self[0].datas.decode('base64')) #img.resize(dest_width,dest_height) #~ self[0].image = img.make_blob(format='jpg').encode('base64') img = Image(blob=self[0].datas.decode('base64'),resolution=(RESOLUTION,RESOLUTION)) img.background_color = Color('white') self[0].image = img.make_blob(format='jpg').encode('base64')
def make_anim(): paths = glob('*.png') image = Image(filename=paths[0]) anim = image.convert('gif') for p in paths[1:]: anim.sequence.append( Image(filename=p).convert('gif')) # lined up manually for once off capture anim.crop(left=80, top=1030, width=585, height=140) import IPython IPython.embed() save(anim)
def resizeCanvas(image, new_width, new_height): if image.width > new_width: image.crop(0, 0, new_width, image.height) if image.height > new_height: image.crop(0, 0, image.width, new_height) if image.width == new_width and image.height == new_height: return image canvas = Image(width=new_width, height=new_height) canvas.composite(image, 0, 0) return canvas
''' End of configuration ''' if DEBUG_DIR: os.mkdir(DEBUG_DIR) pair_file = open(PAIR_FILE, 'a') view_file = open(VIEW_FILE, 'a') mask_input = None if MASK_IMAGE_FILE: mask_input = Image(filename=MASK_IMAGE_FILE) mask_input.crop(CROP_LEFT, CROP_TOP, mask_input.width - CROP_RIGHT, mask_input.height - CROP_BOTTOM) mask_input.rotate(ROTATE) background = None background_cv = None for led_index in range(START_LED, TOTAL_LEDS): # resolve background potential_background = "%s/%05d-background.jpg" % (PHOTO_DIR, led_index) if os.path.isfile(potential_background): background = Image(filename=potential_background) background.crop(CROP_LEFT, CROP_TOP, background.width-CROP_RIGHT, background.height-CROP_BOTTOM) background.rotate(ROTATE) if mask_input: background.composite(mask_input)
def _draw(self, strokes, lines, filename, line_num, stroke_colors=None, stroke_widths=None): stroke_colors = stroke_colors or ['black'] * 4 stroke_widths = stroke_widths or [2] * 4 i = 1 #i+=1 img_large = cv2.imread("templates/large1.jpg") l_img = cv2.imread("large1.jpg", 0) for offsets, line, color, width in zip(strokes, lines, stroke_colors, stroke_widths): svgfil = 'p' + str(i) + '.svg' if i == 1: line_height = 30 view_width = 200 dwg1 = svgwrite.Drawing(filename=svgfil) dwg = dwg1 if i == 2: line_height = 30 view_width = 300 dwg2 = svgwrite.Drawing(filename=svgfil) dwg = dwg2 if i == 3: line_height = 60 view_width = 450 dwg3 = svgwrite.Drawing(filename=svgfil) dwg = dwg3 if i == 4: line_height = 60 view_width = 450 dwg4 = svgwrite.Drawing(filename=svgfil) dwg = dwg4 #line_height = 50 #view_width = 300 view_height = line_height * 2 dwg.viewbox(width=view_width, height=view_height) dwg.add( dwg.rect(insert=(0, 0), size=(view_width, view_height), fill='white')) initial_coord = np.array([0, -(3 * line_height / 4)]) if not line: initial_coord[1] -= line_height continue offsets[:, :2] *= 1.1 strokes = drawing.offsets_to_coords(offsets) strokes = drawing.denoise(strokes) strokes[:, :2] = drawing.align(strokes[:, :2]) strokes[:, 1] *= -1 strokes[:, :2] -= strokes[:, :2].min() + initial_coord strokes[:, 0] += (view_width - strokes[:, 0].max()) / 2 prev_eos = 1.0 p = "M{},{} ".format(0, 0) for x, y, eos in zip(*strokes.T): p += '{}{},{} '.format('M' if prev_eos == 1.0 else 'L', x, y) prev_eos = eos if i == 1: path1 = svgwrite.path.Path(p) path1 = path1.stroke(color=color, width=width, linecap='round').fill("none") dwg.add(path1) if i == 2: path2 = svgwrite.path.Path(p) path2 = path2.stroke(color=color, width=width, linecap='round').fill("none") dwg.add(path2) if i == 3: path3 = svgwrite.path.Path(p) path3 = path3.stroke(color=color, width=width, linecap='round').fill("none") dwg.add(path3) if i == 4: path4 = svgwrite.path.Path(p) path4 = path4.stroke(color=color, width=width, linecap='round').fill("none") dwg.add(path4) #initial_coord[1] -= line_height dwg.save() with Image(filename=svgfil, format='svg') as img: img.format = 'png' img.save(filename="s.png") s_img = cv2.imread("s.png", 0) #control placement of text on the form if i == 1: x_offset = 135 y_offset = 50 if i == 2: x_offset = 155 y_offset = 110 if i == 3: x_offset = 150 y_offset = 300 if i == 4: x_offset = 150 y_offset = 390 l_img[y_offset:y_offset + s_img.shape[0], x_offset:x_offset + s_img.shape[1]] = s_img outfile = "output/" + filename i = i + 1 cv2.imwrite(outfile, l_img) s_img = np.ones(s_img.shape) * int(255) cv2.imwrite("s.png", s_img)
def test_empty_image(): with Image() as img: assert img.size == (0, 0) assert repr(img) == '<wand.image.Image: (empty)>'
def test_data_url(): with Image(filename='rose:') as img: img.format = 'PNG' data = img.data_url() assert data.startswith('data:image/png;base64,')
data = response.read() # a `bytes` object out_file.write(data) # In[4]: print(glob.glob('5645173.pdf')) print(glob.glob('5645177.pdf')) # # Now let's convert the downloaded pdf to images # In[8]: from __future__ import print_function from wand.image import Image with Image(filename='5645173.pdf', resolution=300) as img: img.compression_quality = 99 print('width =', img.width) print('height =', img.height) print('pages = ', len(img.sequence)) print('resolution = ', img.resolution) with img.convert('png') as converted: converted.save(filename='5645173.png') file_name1 = '5645173.png' # In[9]: from __future__ import print_function from wand.image import Image
def test_colorspace_get(fx_asset): """Gets the image colorspace""" with Image(filename=str(fx_asset.join('mona-lisa.jpg'))) as img: assert img.colorspace.endswith('rgb')
def process(self, pdf_filename, pdf_resolution, imageformat, do_orientation): final_text = "" image_pdf = Image(filename=pdf_filename, resolution=pdf_resolution) image_page = image_pdf.convert(imageformat) page = 1 process_start = time.time() for img in image_page.sequence: img_per_page = Image(image=img) img_per_page.type = 'grayscale' img_per_page.depth = 8 img_per_page.density = 300 try: img_per_page.level(black=0.3, white=1.0, gamma=1.5, channel=None) except AttributeError as e: print("Update Wand library: %s" % e) img_per_page.save(filename="buffer.png") page_start = time.time() txt = self.image2txt_pyocr( img_per_page.make_blob("png"), do_orientation) page_elaboration = time.time() - page_start print("page %s - size %s - process %2d sec. - text %s" % (page, img_per_page.size, page_elaboration, len(txt))) final_text += "%s\n" % txt page += 1 img.destroy() process_end = time.time() - process_start print("Total elaboration time: %s" % process_end) return final_text
def test_dispose(fx_asset): with Image(filename=str(fx_asset.join('nocomments.gif'))) as img: assert img.dispose == 'none' img.dispose = 'background' assert img.dispose == 'background'
def test_format_get(fx_asset): """Gets the image format.""" with Image(filename=str(fx_asset.join('mona-lisa.jpg'))) as img: assert img.format == 'JPEG' with Image(filename=str(fx_asset.join('croptest.png'))) as img: assert img.format == 'PNG'
def test_depth_set(fx_asset): """Sets the image depth""" with Image(filename=str(fx_asset.join('mona-lisa.jpg'))) as img: img.depth = 16 assert img.depth == 16
def test_delay_set_get(fx_asset): with Image(filename=str(fx_asset.join('nocomments.gif'))) as img: img.delay = 10 assert img.delay == 10
def test_alpha_channel_get(fx_asset): """Checks if image has alpha channel.""" with Image(filename=str(fx_asset.join('watermark.png'))) as img: assert img.alpha_channel is True with Image(filename=str(fx_asset.join('mona-lisa.jpg'))) as img: assert img.alpha_channel is False
def convert_image( pngfile, pf, outdir=".", resize=1000, format="jpeg", rotate=0, rows=":", cols=":", labelrows=None, labelcols=None, ): resizefile = op.join(outdir, pf + ".resize.jpg") mainfile = op.join(outdir, pf + ".main.jpg") labelfile = op.join(outdir, pf + ".label.jpg") img = Image(filename=pngfile) exif = dict((k, v) for k, v in img.metadata.items() if k.startswith("exif:")) # Rotation, slicing and cropping of main image if rotate: img.rotate(rotate) if resize: w, h = img.size if min(w, h) > resize: if w < h: nw, nh = resize, resize * h / w else: nw, nh = resize * w / h, resize img.resize(nw, nh) logging.debug( "Image `{0}` resized from {1}px:{2}px to {3}px:{4}px".format( pngfile, w, h, nw, nh ) ) img.format = format img.save(filename=resizefile) rimg = img.clone() if rows != ":" or cols != ":": w, h = img.size ra, rb = slice(rows, h) ca, cb = slice(cols, w) # left, top, right, bottom logging.debug("Crop image to {0}:{1} {2}:{3}".format(ra, rb, ca, cb)) img.crop(ca, ra, cb, rb) img.format = format img.save(filename=mainfile) else: mainfile = resizefile # Extract text labels from image if labelrows or labelcols: w, h = rimg.size if labelrows and not labelcols: labelcols = ":" if labelcols and not labelrows: labelrows = ":" ra, rb = slice(labelrows, h) ca, cb = slice(labelcols, w) logging.debug("Extract label from {0}:{1} {2}:{3}".format(ra, rb, ca, cb)) rimg.crop(ca, ra, cb, rb) rimg.format = format rimg.save(filename=labelfile) else: labelfile = None return resizefile, mainfile, labelfile, exif
def test_colors(fx_asset): with Image(filename=str(fx_asset.join('trim-color-test.png'))) as img: assert img.colors == 2
def ImageMagicConvert(): ''' ''' from wand.image import Image from wand.color import Color from wand.display import display dest_path = "D:/" test_file = "d:/___TMP_CRY_ASSETS/Assets/models/Nature/Trees/Big/Textures/Tree10_ddna.tif" filename, file_extension = os.path.splitext(os.path.basename(test_file)) base_filename = filename[0:-5] original = Image(filename=test_file) gloss_img = original.clone() # gloss_img.type = 'grayscale' # gloss_img.depth = 8 gloss_img.alpha_channel = 'off' converted = original.convert('tga') # converted.format = 'tga' # gloss_img.composite_channel("green", original, 'copy') # ================================================================================= # gloss_img = converted.fx("p.g:0", channel="red") #fill red channel # gloss_img = gloss_img.fx("p.g:0", channel="blue") # gloss_img.alpha_channel = 'off' # gloss_img.level(0, 0, 1.0, 'red') #fill red channel white # gloss_img.level(1, 0, 0.0, 'red') #fill red channel black # gloss_img.level(1, 0, 1.0, 'red') #invert red channel # ================================================================================= alpha_image = original.clone() alpha_image.alpha_channel = 'extract' alpha_image.convert('RGB') gloss_img.composite_channel("green", alpha_image, 'copy') gloss_img.level(1, 0, 0.0, 'red') #fill red channel black gloss_img.level(1, 0, 0.0, 'blue') # display(gloss_img) # return from wand.api import library # display image # from wand.display import display # display(gloss_img) # alpha_image = converted.channel_images['alpha'] # with converted.channel_images['red'] as alpha_image: # alpha_image # shading (R-metalness, G-roughness, B-specular) exported_file = os.path.join(dest_path, base_filename + "_sh" + ".tga") gloss_img.save(filename=exported_file) exported_file = os.path.join(dest_path, base_filename + "_n.tga") # converted.alpha_channel = False # converted.alpha_channel = 'extract' # converted.alpha_channel = 'remove' converted.alpha_channel = 'off' converted.save(filename=exported_file) pass
from wand.image import Image from PIL import Image as PI import pyocr import pyocr.builders import io tool = pyocr.get_available_tools()[0] lang = tool.get_available_languages()[0] print(lang) req_image = [] final_text = [] image_pdf = Image( filename="/Users/Hansen/Desktop/Machine_Learning_Python/test.pdf", resolution=300) image_jpeg = image_pdf.convert('jpeg') for img in image_jpeg.sequence: img_page = Image(image=img) req_image.append(img_page.make_blob('jpeg')) for img in req_image: txt = tool.image_to_string(PI.open(io.BytesIO(img)), lang=lang, builder=pyocr.builders.TextBuilder()) final_text.append(txt) print(final_text)
from wand.image import Image import os pdf_file = "mypdf.pdf" files = [] with(Image(filename=pdf_file, resolution = 500)) as conn: for index, image in enumerate(conn.sequence): image_name = os.path.splitext(pdf_file)[0] + str(index + 1) + '.png' Image(image).save(filename = image_name) files.append(image_name)
import sys from wand.image import Image if len(sys.argv) < 3: print('{0} <ORIGINAL PATH> <SCALE>'.format(sys.argv[0])) sys.exit() original_path=sys.argv[1] scale=float(sys.argv[2]) #크기 조정 배율. 소수일 수도 있으므로. with Image(filename=original_path) as image: print("Original : {0}, {1}".format(image.format, image.size)) #복사본을 만든 후 resize()를 호출. resized=image.clone() resized.resize(int(image.width*scale), int(image.height*scale)) print("Resized : {0}, {1}".format(resized.format, resized.size)) resized.save(filename='{0}.{1}'.format(scale, original_path))
def test_numpy_array_hairpinning(): with Image(filename='rose:') as left: with Image.from_array(left) as right: assert left.size == right.size
def request_handler(event, context): user_id = int(event['user']['id']) caption = str(event['caption']) s3_image_url = event['imageUrl'] data_items = s3_image_url.split('/') photo_name = data_items[-1] bucket_name = data_items[-2] can_be_shown = True filtered_image_bucket_name = 'rekognition-filtered-photos' client = boto3.client('rekognition', 'us-east-1') response = client.detect_moderation_labels(Image={'S3Object': {'Bucket': bucket_name, 'Name': photo_name}}) moderation_labels = response['ModerationLabels'] parent_labels = ['Explicit Nudity', 'Suggestive'] explicit_content_labels = ['Nudity', 'Graphic Male Nudity', 'Graphic Female Nudity', 'Sexual Activity', 'Partial Nudity', 'Female Swimwear Or Underwear', 'Male Swimwear Or Underwear', 'Revealing Clothes'] for label in moderation_labels: label_name = label['Name'] parent_name = label['ParentName'] confidence = float(label['Confidence']) if parent_name in parent_labels: if label_name in explicit_content_labels and confidence >= 95: can_be_shown = False break if can_be_shown: s3_connection = boto3.resource('s3') s3_object = s3_connection.Object(bucket_name, photo_name) s3_image_object = s3_object.get() with Image(blob=s3_image_object['Body'].read()) as image: resized_image = resize_image(image, 256, 256) resized_data = resized_image.make_blob() s3_resized_object = s3_connection.Object(filtered_image_bucket_name, photo_name) s3_resized_object.put(ACL='authenticated-read', Body=resized_data) url = """https://s3.amazonaws.com/{}/{}""".format(filtered_image_bucket_name, photo_name) try: print('Connecting To DB') host = config.mysql_config['host'] user = config.mysql_config['user'] password = config.mysql_config['password'] db = config.mysql_config['db'] port = config.mysql_config['port'] conn = pymysql.connect(host=host, port=port, user=user, passwd=password, db=db) cur = conn.cursor() print('Connected') print('Current DateTime:') now = datetime.now(timezone('Asia/Singapore')) print(now) cur.execute("""insert into posts(caption,like_count,created_date,posted_image,user_id) values(%s,%s,%s,%s,%s)""",(caption, 0, now, url, user_id)) print('Query Execution Completed') except Exception, e: print('error') print(str(e)) finally:
def create_cover(issuefile=None, refresh=False): if lazylibrarian.CONFIG['IMP_CONVERT'] == 'None': # special flag to say "no covers required" return if issuefile is None or not os.path.isfile(issuefile): logger.debug('No issuefile %s' % issuefile) return base, extn = os.path.splitext(issuefile) if not extn: logger.debug('Unable to create cover for %s, no extension?' % issuefile) return coverfile = base + '.jpg' if os.path.isfile(coverfile): if refresh: os.remove(coverfile) else: logger.debug('Cover for %s exists' % issuefile) return # quit if cover already exists and we didn't want to refresh logger.debug('Creating cover for %s' % issuefile) data = '' # result from unzip or unrar extn = extn.lower() if extn in ['.cbz', '.epub']: try: data = zipfile.ZipFile(issuefile) except Exception as why: logger.debug("Failed to read zip file %s, %s %s" % (issuefile, type(why).__name__, str(why))) data = '' elif extn in ['.cbr']: try: # unrar will complain if the library isn't installed, needs to be compiled separately # see https://pypi.python.org/pypi/unrar/ for instructions # Download source from http://www.rarlab.com/rar_add.htm # note we need LIBRARY SOURCE not a binary package # make lib; sudo make install-lib; sudo ldconfig # lib.unrar should then be able to find libunrar.so from lib.unrar import rarfile data = rarfile.RarFile(issuefile) except Exception as why: logger.debug("Failed to read rar file %s, %s %s" % (issuefile, type(why).__name__, str(why))) data = '' if data: img = '' try: for member in data.namelist(): memlow = member.lower() if '-00.' in memlow or '000.' in memlow or 'cover.' in memlow: if memlow.endswith('.jpg') or memlow.endswith('.jpeg'): img = data.read(member) break if img: with open(coverfile, 'wb') as f: f.write(img) return else: logger.debug("Failed to find image in %s" % issuefile) except Exception as why: logger.debug("Failed to extract image from %s, %s %s" % (issuefile, type(why).__name__, str(why))) elif extn == '.pdf': generator = "" if len(lazylibrarian.CONFIG['IMP_CONVERT']): # allow external convert to override libraries generator = "external program: %s" % lazylibrarian.CONFIG['IMP_CONVERT'] if "gsconvert.py" in lazylibrarian.CONFIG['IMP_CONVERT']: msg = "Use of gsconvert.py is deprecated, equivalent functionality is now built in. " msg += "Support for gsconvert.py may be removed in a future release. See wiki for details." logger.warn(msg) converter = lazylibrarian.CONFIG['IMP_CONVERT'] postfix = '' # if not os.path.isfile(converter): # full path given, or just program_name? # converter = os.path.join(os.getcwd(), lazylibrarian.CONFIG['IMP_CONVERT']) if 'convert' in converter and 'gs' not in converter: # tell imagemagick to only convert first page postfix = '[0]' try: params = [converter, '%s%s' % (issuefile, postfix), '%s' % coverfile] res = subprocess.check_output(params, stderr=subprocess.STDOUT) if res: logger.debug('%s reports: %s' % (lazylibrarian.CONFIG['IMP_CONVERT'], res)) except Exception as e: # logger.debug(params) logger.debug('External "convert" failed %s %s' % (type(e).__name__, str(e))) elif platform.system() == "Windows": GS = os.path.join(os.getcwd(), "gswin64c.exe") generator = "local gswin64c" if not os.path.isfile(GS): GS = os.path.join(os.getcwd(), "gswin32c.exe") generator = "local gswin32c" if not os.path.isfile(GS): params = ["where", "gswin64c"] try: GS = subprocess.check_output(params, stderr=subprocess.STDOUT).strip() generator = "gswin64c" except Exception as e: logger.debug("where gswin64c failed: %s %s" % (type(e).__name__, str(e))) if not os.path.isfile(GS): params = ["where", "gswin32c"] try: GS = subprocess.check_output(params, stderr=subprocess.STDOUT).strip() generator = "gswin32c" except Exception as e: logger.debug("where gswin32c failed: %s %s" % (type(e).__name__, str(e))) if not os.path.isfile(GS): logger.debug("No gswin found") generator = "(no windows ghostscript found)" else: try: params = [GS, "--version"] res = subprocess.check_output(params, stderr=subprocess.STDOUT) logger.debug("Found %s [%s] version %s" % (generator, GS, res)) generator = "%s version %s" % (generator, res) issuefile = issuefile.split('[')[0] params = [GS, "-sDEVICE=jpeg", "-dNOPAUSE", "-dBATCH", "-dSAFER", "-dFirstPage=1", "-dLastPage=1", "-dUseCropBox", "-sOutputFile=%s" % coverfile, issuefile] res = subprocess.check_output(params, stderr=subprocess.STDOUT) if not os.path.isfile(coverfile): logger.debug("Failed to create jpg: %s" % res) except Exception: # as why: logger.debug("Failed to create jpg for %s" % issuefile) logger.debug('Exception in gswin create_cover: %s' % traceback.format_exc()) else: # not windows try: # noinspection PyUnresolvedReferences,PyUnresolvedReferences,PyUnresolvedReferences from wand.image import Image interface = "wand" except ImportError: try: # No PythonMagick in python3 # noinspection PyUnresolvedReferences import PythonMagick interface = "pythonmagick" except ImportError: interface = "" try: if interface == 'wand': generator = "wand interface" # noinspection PyUnboundLocalVariable with Image(filename=issuefile + '[0]') as img: img.save(filename=coverfile) elif interface == 'pythonmagick': generator = "pythonmagick interface" # noinspection PyUnboundLocalVariable,PyArgumentList img = PythonMagick.Image() # PythonMagick requires filenames to be str, not unicode if type(issuefile) is unicode: issuefile = unaccented_str(issuefile) if type(coverfile) is unicode: coverfile = unaccented_str(coverfile) img.read(issuefile + '[0]') img.write(coverfile) else: GS = os.path.join(os.getcwd(), "gs") generator = "local gs" if not os.path.isfile(GS): GS = "" params = ["which", "gs"] try: GS = subprocess.check_output(params, stderr=subprocess.STDOUT).strip() generator = GS except Exception as e: logger.debug("which gs failed: %s %s" % (type(e).__name__, str(e))) if not os.path.isfile(GS): logger.debug("Cannot find gs") generator = "(no gs found)" else: params = [GS, "--version"] res = subprocess.check_output(params, stderr=subprocess.STDOUT) logger.debug("Found gs [%s] version %s" % (GS, res)) generator = "%s version %s" % (generator, res) issuefile = issuefile.split('[')[0] params = [GS, "-sDEVICE=jpeg", "-dNOPAUSE", "-dBATCH", "-dSAFER", "-dFirstPage=1", "-dLastPage=1", "-dUseCropBox", "-sOutputFile=%s" % coverfile, issuefile] res = subprocess.check_output(params, stderr=subprocess.STDOUT) if not os.path.isfile(coverfile): logger.debug("Failed to create jpg: %s" % res) except Exception as e: logger.debug("Unable to create cover for %s using %s %s" % (issuefile, type(e).__name__, generator)) logger.debug('Exception in create_cover: %s' % traceback.format_exc()) if os.path.isfile(coverfile): setperm(coverfile) logger.debug("Created cover for %s using %s" % (issuefile, generator)) return # if not recognised extension or cover creation failed try: shutil.copyfile(os.path.join(lazylibrarian.PROG_DIR, 'data/images/nocover.jpg'), coverfile) setperm(coverfile) except Exception as why: logger.debug("Failed to copy nocover file, %s %s" % (type(why).__name__, str(why))) return
def generate(url): hdr = { 'User-Agent':'Mozilla/5.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' } req = urllib2.Request(url, headers=hdr) f = urllib2.urlopen(req) im = pilimg.open(f) key = ''.join([random.choice(string.ascii_letters) for n in range(10)]) im.save('res/' + key + ".png","png") with Image(filename='res/%s.png' % key) as img: if img.sequence: img = Image(image=img.sequence[0]) img.resize(300,300) with Drawing() as draw: draw.fill_color = Color('#f00') draw.fill_opacity = 0.4 draw.rectangle(0, 0, img.width, img.height) draw(img) with Image(filename='res/generate/gulag.png') as sickle: sickle.resize(200,200) img.composite(sickle, 50, 50) img.format = 'png' img.save(filename='res/gulag.png') os.remove('res/' + key + '.png')
# -stroke black -annotate +168+68 o -stroke none -annotate +168+68 o \ # -stroke black -annotate +193+68 n -stroke none -annotate +193+68 n \ # -stroke black -annotate +223+68 y -stroke none -annotate +223+68 y \ # font_overlapped.jpg def drawcharacter(draw, char, x, y, color): draw.stroke_color = color draw.text(x, y, char) draw.stroke_color = Color('none') draw.text(x, y, char) w = 320 h = 100 with Image(width=w, height=h, background=Color('lightblue')) as img: with Drawing() as draw: draw.font = 'Candice' draw.font_size = 72 draw.gravity = 'forget' draw.fill_color = Color('white') draw.stroke_width = 4 drawcharacter(draw, 'A', 26, 68, Color('black')) drawcharacter(draw, 'n', 90, 68, Color('black')) drawcharacter(draw, 't', 120, 68, Color('black')) drawcharacter(draw, 'h', 138, 68, Color('black')) drawcharacter(draw, 'o', 168, 68, Color('black')) drawcharacter(draw, 'n', 193, 68, Color('black')) drawcharacter(draw, 'y', 223, 68, Color('black')) draw(img) img.save(filename='sample20.png')
def convert_pdf_to_image(fn): #print 'Converting PDF to image' with Image(filename=fn, resolution=300) as img: return img.convert('jpeg')
def test_slice_clone(fx_asset): """Clones using slicing.""" with Image(filename=str(fx_asset.join('mona-lisa.jpg'))) as img: with img[:, :] as cloned: assert img.size == cloned.size
def test_colorspace_set(fx_asset): """Sets the image colorspace""" with Image(filename=str(fx_asset.join('mona-lisa.jpg'))) as img: img.colorspace = 'cmyk' assert img.colorspace == 'cmyk'
dbdpath = args.dbdpath background = args.backgroundimage dbdpath = os.path.join(dbdpath, 'DeadByDaylight/Content/UI/Icons/Perks') basepath = os.path.dirname(os.path.realpath(__file__)) copyDir = os.path.join(basepath, 'Perks') copy_tree(dbdpath, copyDir) zipf = zipfile.ZipFile('Perks.zip', 'w', zipfile.ZIP_DEFLATED) zipdir('Perks', zipf) zipf.close() dirs = [] for filename in os.listdir('Perks'): with Image(filename=background) as bg: bg.resize(256, 256) path = os.path.join(basepath, "Perks", filename) if os.path.isdir(path): dirs.append(path) continue with Image(filename="Perks/" + filename) as fg: bg.composite(fg, left=0, top=0) bg.save(filename="Perks/" + filename) for directory in dirs: for filename in os.listdir(directory): with Image(filename=background) as bg: bg.resize(256, 256) path = os.path.join(directory, filename) with Image(filename=path) as fg:
from wand.image import Image import image_slicer from fpdf import FPDF import os filename = raw_input("Enter file name:") inputpdf = PdfFileReader(open(filename, "rb")) numPages = inputpdf.numPages pagesPerSlide = 4 for i in xrange(numPages): output = PdfFileWriter() output.addPage(inputpdf.getPage(i)) with open("trial-page%s.pdf" % i, "wb") as outputStream: output.write(outputStream) for i in xrange(numPages): with Image(filename="trial-page%s.pdf" % i) as img: with img.convert('png') as converted: converted.save(filename="trial-page%s.png" % i) for i in xrange(numPages): image_slicer.slice("trial-page%s.png" % i, 4) imlist = [] for i in xrange(numPages): imlist.append("trial-page%s_01_01.png" % i) imlist.append("trial-page%s_01_02.png" % i) imlist.append("trial-page%s_02_01.png" % i) imlist.append("trial-page%s_02_02.png" % i) pdf = FPDF(format='A4')
def test_compression_quality_get(fx_asset): """Gets the image compression quality.""" with Image(filename=str(fx_asset.join('mona-lisa.jpg'))) as img: assert img.compression_quality == 80
help='Log debugging information') parser.add_argument('image', type=argparse.FileType('rb'), help='Source image') args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) layers = [] tile_size = args.tile_size logging.info("tile size: %dx%d", tile_size, tile_size) with Image(file=args.image) as source: logging.info("image size: %dx%d", source.width, source.height) # every zoom level has 2x more tiles max_zoom = math.ceil(math.log(max(source.size) / args.tile_size, 2)) logging.info("zoom levels: 1-%d", max_zoom) image_size = args.tile_size * (2 ** max_zoom) offset_x, offset_y = tuple((image_size - orig) // 2 for orig in source.size) logging.info("tiled size: %dx%d-%d-%d", image_size, image_size, offset_x, offset_y) layers.append({ "name": "???", "URL": os.path.basename(args.image.name), "width": source.width, "height": source.height,