def pic_rect(content, x, y, w, h, max_length=120, min_length=70, quality=88): im = open_pic(content) try: #cannot less than min_length w = max(w, min_length) h = max(h, min_length) max_l = max(w, h) #crop a rect new = im.crop((x, y, x+w, y+h)) #zoom_out if max_l > max_length: ww = w hh = h # w > h if max_l > h: hh = hh * max_length // ww ww = max_length # h > w elif max_l > w: ww = ww * max_l // hh hh = max_length else: ww = hh = max_length new = new.resize((ww, hh), Image.ANTIALIAS) ie = ImageEnhance.Sharpness(new) new = ie.enhance(1.2) f = StringIO() new.save(f, 'JPEG', quality=quality) return f.getvalue() except IOError, e: if e.message == "cannot read interlaced PNG files": raise UnknownPictureError() else: raise
def ctpn(sess, net, image_name): timer = Timer() timer.tic() img = cv2.imread(image_name) img, scale = resize_im(img, scale=TextLineCfg.SCALE, max_scale=TextLineCfg.MAX_SCALE) #将OPENCV图像转换为PIL图像, pil_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) #求图片清晰度 imageVar = cv2.Laplacian(img, cv2.CV_64F).var() if imageVar <= 5000: pil_img = ImageEnhance.Sharpness(pil_img).enhance(3.0) #将PIL图像转换为opencv图像 img = cv2.cvtColor(np.asarray(pil_img), cv2.COLOR_RGB2BGR) scores, boxes = test_ctpn(sess, net, img) textdetector = TextDetector() boxes = textdetector.detect(boxes, scores[:, np.newaxis], img.shape[:2]) draw_boxes(img, image_name, boxes, scale) timer.toc() print(('Detection took {:.3f}s for ' '{:d} object proposals').format(timer.total_time, boxes.shape[0]))
def __init__(self, **kwargs): kwargs.setdefault('filename', os.path.join('..', 'photoo', 'photo1.jpg')) if kwargs.get('filename') is None: raise Exception('No filename given to MTScatterImage') kwargs.setdefault('loader', None) super(ImageScatter, self).__init__(**kwargs) self.touch_positions = {} self.pim = Image.open(kwargs.get('filename')) self.contrast_enh = ImageEnhance.Contrast(self.pim) self.pim = self.contrast_enh.enhance(1.0) self.bright_enh = ImageEnhance.Brightness(self.pim) self.pim = self.bright_enh.enhance(1.0) self.color_enh = ImageEnhance.Color(self.pim) self.pim = self.color_enh.enhance(1.0) self.sharp_enh = ImageEnhance.Sharpness(self.pim) self.pim = self.sharp_enh.enhance(1.0) self.bdata = self.pim.tostring() self.img = ImageData(self.pim.size[0], self.pim.size[1], 'RGB', self.bdata, pitch=-self.pim.size[0] * 3) self.image = pyglet.sprite.Sprite(self.img) self.width = self.pim.size[0] self.height = self.pim.size[1]
def tesser_ocr(inputfile): im = Image.open(inputfile) if im.size[0] >= 500 or im.size[1] >= 100: scale = 1.0 else: scale = max( float(500) / float(im.size[0]), float(100) / float(im.size[1])) im_resized = im.resize((int(scale * im.size[0]), int(scale * im.size[1])), Image.ANTIALIAS) #将PIL图像转换为opencv图像 cv2_img = cv2.cvtColor(np.asarray(im_resized), cv2.COLOR_RGB2BGR) #求图片清晰度 imageVar = cv2.Laplacian(cv2_img, cv2.CV_64F).var() if imageVar <= 2000: im_resized = ImageEnhance.Sharpness(im_resized).enhance(3.0) im_gray = im_resized.convert("L") im_binary = binarizing(im_gray, 127) text = pytesseract.image_to_string(im_binary, lang="chi_sim+eng", config="-psm 7") return text
def do_sharpness(self): """usage: sharpness <image:pic1> Enhance sharpness in the top image. """ import ImageEnhance factor = float(self.do_pop()) image = self.do_pop() enhancer = ImageEnhance.Sharpness(image) self.push(enhancer.enhance(factor))
def sharpen(image): """Return a sharpened copy of the image and close the original image.""" try: sharpener = ImageEnhance.Sharpness(image) sharpened_image = sharpener.enhance(1.6) close(image) return sharpened_image except Exception, e: _log.exception(e) return image
def sharpen_image(self, value): print "dans sharpen image" if self.current_image_entity == None: img = Image.open(self.cureent_image_path) else: img = self.current_image_entity #print img amelioration = ImageEnhance.Sharpness(img) img_2 = amelioration.enhance(value) #img_2.show() self.current_image_entity = img_2 self.old_entity = img return img_2
def resizeImage(fsrc, ftgt, max_width, max_height, quality, sharpness=1.6): """ Resize image fsrc (path of file), save it to ftgt; Let the maximal dimensions of image be (max_width,max_height), the resulting image quality 'quality', and do a image sharpening with 'sharpness' parameter, prior to saving. """ #os.system("convert '"+fsrc+"' -filter Lanczos -resize "+max_width+"x"+max_height+" -unsharp 0x0.6+1.0 -quality "+quality+" '"+ftgt+"'") iSrc = Image.open(fsrc) w = iSrc.size[0] h = iSrc.size[1] if w >= h and w > max_width: h = h * max_width / w w = max_width elif h >= w and h > max_height: w = w * max_height / h h = max_height iSrc = iSrc.resize((w, h), Image.ANTIALIAS) sharpener = ImageEnhance.Sharpness(iSrc) iSrcSharp = sharpener.enhance(sharpness) iSrcSharp.save(ftgt, quality=quality) return
def wobbly_copy(src, wob, col, scale, ang): x, y = src.size f = random.uniform(4 * scale, 5 * scale) p = random.uniform(0, math.pi * 2) rr = ang + random.uniform(-10, 10) # vary, but not too much int_d = Image.new('RGB', src.size, 0) # a black rectangle rot = src.rotate(rr, Image.BILINEAR) # Do a cheap bounding-box op here to try to limit work below bbx = rot.getbbox() if bbx == None: return src else: l, t, r, b = bbx # and only do lines with content on for i in range(t, b + 1): # Drop a scan line in xoff = int(math.sin(p + (i * f / y)) * wob) xoff += int(random.uniform(-wob * 0.5, wob * 0.5)) int_d.paste(rot.crop((0, i, x, i + 1)), (xoff, i)) # try to stop blurring from building up int_d = int_d.rotate(-rr, Image.BILINEAR) enh = ImageEnhance.Sharpness(int_d) return enh.enhance(2)
def process_image(source, destination): constant_width = 744 try: # convert to black and white image = Image.open(source, "r").convert("L") # rotate the image if it's a double-page if is_landscape(image): image = image.transpose(Image.ROTATE_90) # Resize the image to fit on a kindle. image = image.resize(fill_width(constant_width, *image.size), Image.ANTIALIAS) # Do some slight sharpening. image = ImageEnhance.Sharpness(image).enhance(2) image.save(destination) return True except: print "invalid file, removing", source #os.remove(source) return False
def enhance(pixbuf, brightness=1.0, contrast=1.0, saturation=1.0, sharpness=1.0, autocontrast=False): """Return a modified pixbuf from <pixbuf> where the enhancement operations corresponding to each argument has been performed. A value of 1.0 means no change. If <autocontrast> is True it overrides the <contrast> value, but only if the image mode is supported by ImageOps.autocontrast (i.e. it is L or RGB.) """ im = pixbuf_to_pil(pixbuf) if brightness != 1.0: im = ImageEnhance.Brightness(im).enhance(brightness) if autocontrast and im.mode in ('L', 'RGB'): im = ImageOps.autocontrast(im, cutoff=0.1) elif contrast != 1.0: im = ImageEnhance.Contrast(im).enhance(contrast) if saturation != 1.0: im = ImageEnhance.Color(im).enhance(saturation) if sharpness != 1.0: im = ImageEnhance.Sharpness(im).enhance(sharpness) return pil_to_pixbuf(im)
def _sharpen_fired(self): print "Sharpening the image!" im = Image.open("image.jpg") im_sharpness_enhanced = ImageEnhance.Sharpness(im).enhance(2) im_sharpness_enhanced.save("image.jpg", "JPEG") self.display_image()
(options.res_size, options.res_size), Image.ANTIALIAS).filter(ImageFilter.MedianFilter(options.kernel_size)) print "done." print "applying threshold... ", hist = scipy.ndimage.filters.gaussian_filter1d(np.array( imGray.histogram()[100:200]), sigma=10) val = np.argmin(hist) + options.threshold contrast = ImageEnhance.Contrast(imGray) imGray = contrast.enhance(2.5) sharper = ImageEnhance.Sharpness(imGray) imGray = sharper.enhance(0.5) imGray.save("temp.bmp") im.convert("L").resize((options.res_size, options.res_size), Image.ANTIALIAS).save("temp2.bmp") Img = plt.imread("temp.bmp")[::-1] #Img -= val #Img = Img.clip(min=val) Img2 = plt.imread("temp2.bmp")[::-1] plt.imshow(Img, cmap='gray') plt.draw() plt.savefig("temp6.png") plt.hold(False)
#coding:utf-8 import Image import pytesseract import ImageEnhance img = Image.open('11.png') img = img.convert('RGBA') img = img.convert('L') img.save('end_9.png') sharpness = ImageEnhance.Sharpness(img) # Sharpened img = sharpness.enhance(7.0) img.save('end_0.png') #img = ImageEnhance.Color(img) # Black and white #img = img.enhance(0) img.save('end_1.png') #img = ImageEnhance.Brightness(img) # Increase brightness #img = img.enhance(3) img.save('end_2.png') img = ImageEnhance.Contrast(img) # High contrast img = img.enhance(8) img.save('end_3.png') #img = ImageEnhance.Color(img) #img = img.convert('L')
try: new = im.resize((x, y), Image.ANTIALIAS) except IOError, e: if e.message == "cannot read interlaced PNG files": raise UnknownPictureError() else: raise del im if crop: hx, hy = box_size[0]/2, box_size[1]/2 new = new.crop((x/2-hx, y/2-hy, x/2+hx, y/2+hy)) # adjust the blurred image after resize operation if sharp is not None: ie = ImageEnhance.Sharpness(new) new = ie.enhance(sharp) f = StringIO() new.save(f, 'JPEG', quality=quality) return f.getvalue() ### 计算新图片的尺寸,所有函数均以sizer_开头 def sizer_inner(box_size, original_size): """sub-picture innerconnect the box, same ratio as the original image box_size: (x, y), size of box original_size: (x, y), size of original picture return: (x, y), size of new picture """
def sharpness_img(img_name, new_img='new_img.jpg'): img = Image.open(img_name) sharpness = ImageEnhance.Sharpness(img) sharp_img = sharpness.enhance(7.0) sharp_img.save(new_img)
this_sum_rgb += this_pixel[i,j] return this_sum_rgb raw_pic_total_rgb = get_this_pivot(img) print "raw pic sum rgb is:", raw_pic_total_rgb #pivot = 600.00 / 7518351350 * raw_pic_total_rgb #print "pivot is:", pivot #region = template_img.crop((88,42,91,45)) #r,g,b = img.split() # enhance the pic enhancer = ImageEnhance.Sharpness(img) img = enhancer.enhance(2) #img.show() new_img = img.convert('1') # (1-bit pixels, black and white, stored with one pixel per byte) #new_img = img.filter(ImageFilter.CONTOUR) #new_img.show() converted_pic_total_rgb = get_this_pivot(new_img) print "converted pic sum rgb is:", converted_pic_total_rgb pixel = new_img.load()
#coding=utf-8 import Image, ImageEnhance pic = Image.open("../images/test2.jpg") #亮度增强 brightness = ImageEnhance.Brightness(pic) bright_pic = brightness.enhance(2.0) bright_pic.show() bright_pic.save("../images/test6.jpg") #图像尖锐化 sharpness = ImageEnhance.Sharpness(pic) sharp_pic = sharpness.enhance(5.0) sharp_pic.show() sharp_pic.save("../images/test7.jpg") #对比度增强 contrast = ImageEnhance.Contrast(pic) contrast_pic = contrast.enhance(3.0) contrast_pic.show() contrast_pic.save("../images/test8.jpg")
def scale(source, destination, xy=None, x=None, y=None, square=False, jq=None, **kw): """ Scale an image from C{source} to the given dimensions and write to C{destination}. Automatically converts paletted images to truecolor in order to facilitate filtering. The C{xy} argument is exclusive and can not be used with the C{x} or C{y} arguments. C{x} and C{y} can be used simultaneously. @type source: basestring or file @param source: The path to the source image to scale. @type destination: basestring or file @param destination: The path to save the desired scale into. Parent directories will not be created. @type xy: int @param xy: Scale the image to a given maximum dimension. The longer side will be equal to this, the other will equal or less. @type x: int @param x: Scale the width to the given size. The height is left variable. @type y: int @param y: Scale the height to the given size. The width is left variable. @type square: bool @param square: Crop the resulting scaled image to the square center. @type jq: int @param jq: JPEG quality expressed as a number between zero and 100. The default is 95, unless the largest side is smaller than 1024 whereupon a formula will be used to vary the quality between 60 and 95 based on the size of the image. @type kw: dict @param kw: Additional arguments are passed directly to the C{Image.save} method when writing the scaled image to disk. @return: This function returns nothing. """ image = Image.open(source) if image.mode not in ["RGB", "RGBA"]: image = image.convert('RGB') w, h = image.size factor = 1 if square: l, t = (w / 2) - (min(w, h) / 2), (h / 2) - (min(w, h) / 2) image = image.crop((l, t, l + min(w, h), t + min(w, h))) w = h = min(w, h) if x and factor > int(x) / float(w): factor = int(x) / float(w) if y and factor > int(y) / float(h): factor = int(y) / float(h) if xy: factor = int(xy) / float(max([w, h])) if factor >= 1: image.save(destination, "JPEG", optimize=True, quality=jq and jq or 95, **kw) return thumb = image.resize((int(w * factor), int(h * factor)), Image.ANTIALIAS) if factor < 0.75: enhancer = ImageEnhance.Sharpness(thumb) thumb = enhancer.enhance(2.0 - (factor * 1.333)) if jq is None and max(x, y) < 1024: jquality = int(60 + 35 * (1024.0 / max(w, h))) else: jquality = jq and jq or 95 thumb.save(destination, "JPEG", optimize=True, quality=jquality, **kw)
#coding:utf-8 import Image import pytesseract import ImageEnhance img = Image.open('11.png') img = img.convert('RGBA') img = img.convert('L') img.save('end_9.png') sharpness = ImageEnhance.Sharpness(img)#锐利化 img = sharpness.enhance(7.0) img.save('end_0.png') #img = ImageEnhance.Color(img) #变黑白 #img = img.enhance(0) img.save('end_1.png') #img = ImageEnhance.Brightness(img) # 提高亮度 #img = img.enhance(3) img.save('end_2.png') img = ImageEnhance.Contrast(img) # 高对比 img = img.enhance(8) img.save('end_3.png') #img = ImageEnhance.Color(img) #img = img.convert('L')