def appli_bezier(im, courbe): """ Fonction sur l'histogramme retourne une courbe de bezier traitement 3 composantes identique ou 3 (une par composante r,v,b) """ im.getdata() if isinstance(courbe, list): comp = [fromdata([courbe[v] for v in c.getdata()], "L", im.size) for c in im.split()] return Image.merge("RGB", comp) elif isinstance(courbe, tuple): comp = [fromdata([courbe[i][v] for v in c.getdata()], "L", im.size) for i, c in enumerate(im.split())] return Image.merge("RGB", comp)
def main(exrFilePath): exrFile = OpenEXR.InputFile(exrFilePath) dw = exrFile.header()['dataWindow'] pt = Imath.PixelType(Imath.PixelType.FLOAT) size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1) width, height = size[0], size[1] print size rstr = exrFile.channel("R", pt) gstr = exrFile.channel("G", pt) bstr = exrFile.channel("B", pt) rgbf = [Image.fromstring("F", size, exrFile.channel(c, pt)) for c in "RGB"] for im in rgbf: print im.getextrema() return red, green, blue = array.array("f", rstr), array.array("f", gstr), array.array("f", bstr) floats = array.array("f") for i in range(0, len(red)): floats.append(red[i]) floats.append(green[i]) floats.append(blue[i]) outFile = open(exrFilePath + "_" + str(width) + "x" + str(height) + ".float", "wb") floats.tofile(outFile) outFile.close() return rgbf = [Image.fromstring("F", size, exrFile.channel(c, pt)) for c in "RGB"] extrema = [im.getextrema() for im in rgbf] darkest = min([lo for (lo,hi) in extrema]) lighest = max([hi for (lo,hi) in extrema]) scale = 255 / (lighest - darkest) def normalize_0_255(v): return (v * scale) + darkest rgb8 = [im.point(normalize_0_255).convert("L") for im in rgbf] Image.merge("RGB", rgb8).save(exrFilePath + "_" + str(width) + "x" + str(height) + ".jpg")
def mix(bottom, top): r, g, b, a = top.split() top = Image.merge('RGB', (r,g,b)) mask = Image.merge('L', (a,)) im = bottom.copy() im.paste(top, (0,0), mask) return im
def ConvertEXRToJPG(exrfile, jpgfile): File = OpenEXR.InputFile(exrfile) PixType = Imath.PixelType(Imath.PixelType.FLOAT) DW = File.header()['dataWindow'] Size = (DW.max.x - DW.min.x + 1, DW.max.y - DW.min.y + 1) RedStr = File.channel('R', PixType) GreenStr = File.channel('G', PixType) BlueStr = File.channel('B', PixType) Red = array.array('f', RedStr) Green = array.array('f', GreenStr) Blue = array.array('f', BlueStr) for I in range(len(Red)): Red[I] = EncodeToSRGB(Red[I]) for I in range(len(Green)): Green[I] = EncodeToSRGB(Green[I]) for I in range(len(Blue)): Blue[I] = EncodeToSRGB(Blue[I]) rgbf = [Image.fromstring("F", Size, Red.tostring())] rgbf.append(Image.fromstring("F", Size, Green.tostring())) rgbf.append(Image.fromstring("F", Size, Blue.tostring())) rgb8 = [im.convert("L") for im in rgbf] Image.merge("RGB", rgb8).save(jpgfile, "JPEG", quality=95)
def AlphaOverlay(baseFile, inFile, position, outname=None, format="PNG"): """ Overlay an image with an alpha value onto a background image Params: baseFile -- inFile -- position -- outname=None -- format="PNG" -- Returns: None """ try: bottom = Image.open(baseFile) top = Image.open(inFile) top.load() # Sometimes PIL is lazy and forgets to load the image, so we do it explicitly r, g, b, a = top.split() top = Image.merge("RGB", (r, g, b)) mask = Image.merge("L", (a,)) bottom.paste(top, position, mask) bottom.save(outname, format) except IOError: print "cannot Overlay %s onto %s" % (inFile, baseFile) return None
def load_and_add_alpha(filename): """ load image and add alpha channel """ rgb_chan = Image.open(filename).split() if len(rgb_chan) >= 3: image = Image.merge('RGBA', (rgb_chan[0], rgb_chan[1], rgb_chan[2], alpha_chan[0])) else: image = Image.merge('RGBA', (rgb_chan[0], rgb_chan[0], rgb_chan[0], alpha_chan[0])) return image
def pigment(filepath, savepath, color1, color2='#ffffff'): """Generates colored image from index colored bitmap image. :filepath: base image path. :savepath: colored image path. if empty, show image result. :color1: convert bright color to given hexcolor :color2: convert dark color to given hexcolor """ rgb = (int(color1[1:3], 16), int(color1[3:5], 16), int(color1[5:7], 16)) target_rgb = (int(color2[1:3], 16), int(color2[3:5], 16), int(color2[5:7], 16)) image = Image.open(filepath) image.convert('RGBA') if image.mode == 'LA': _, alpha = image.split() elif image.mode == 'L': _, = image.split() alpha = None elif image.mode == 'RGBA': _r, _g, _b, alpha = image.split() else: overlay = Image.new('RGB', image.size, rgb) overlay.save(savepath) return False overlay = Image.new('RGB', image.size, rgb) R, G, B = overlay.split() if alpha: colored = Image.merge('RGBA', (R, G, B, alpha)) else: colored = Image.merge('RGB', (R, G, B)) if image.mode == 'LA' or image.mode == 'L': target_r, target_g, target_b = target_rgb grays_pix = _.load() colored_pix = colored.load() for x in range(image.size[0]): for y in range(image.size[1]): if image.mode == 'LA': R, G, B, A = colored_pix[x, y] mix = float(grays_pix[x, y])/255.0 colored_pix[x, y] = (int(R+(target_r-R)*mix), int(G+(target_g-G)*mix), int(B+(target_b-B)*mix), A) else: R , G, B = colored_pix[x, y] mix = float(grays_pix[x, y])/255.0 colored_pix[x, y] = (int(R+(target_r-R)*mix), int(G+(target_g-G)*mix), int(B+(target_b-B)*mix)) if savepath: colored.save(savepath) else: colored.show() pass return True
def splice_images(collect_images, map_width, map_height): """ 拼合图片 """ lt = vector2(map_width, map_height) rb = vector2(0, 0) print "需要拼合的图片:" + str(collect_images) for image_info in collect_images: image = Image.open(image_info["image"]) ltx = image_info["x"] lty = image_info["y"] rbx = ltx + image.size[0] rby = lty + image.size[1] if ltx < lt.x: lt.setX(ltx) if lty < lt.y: lt.setY(lty) if rbx > rb.x: rb.setX(rbx) if rby > rb.y: rb.setY(rby) print "拼合图片的左上点: " + str(lt) print "拼合图片的右下点: " + str(rb) collect_image = Image.new("RGBA", (rb.x - lt.x, rb.y - lt.y)) for image_info in collect_images: image = Image.open(image_info["image"]).convert("RGBA") ltx = image_info["x"] - lt.x lty = image_info["y"] - lt.y r, g, b, a = image.split() img = Image.merge("RGB", (r, g, b)) # 使用mask,以使像素混合 mask = Image.merge("L", (a,)) collect_image.paste(img, (ltx, lty, ltx + image.size[0], lty + image.size[1]), mask) # debug # collect_image.save("test.png") return collect_image, lt, rb
def image_handler(auto=True,bmax=None,gmax=None,rmax=None): bfti = FitsToImage(bFits) if not auto or bmax: bfti.scale_data(bmax) bim = bfti.get_image() print 'Blue scale max =\t' + str(bfti.scale_max) # print 'Saving blue image.' # bim.save('btest.png') gfti = FitsToImage(gFits) if not auto or gmax: gfti.scale_data(gmax) gim = gfti.get_image() print 'Green scale max =\t' + str(gfti.scale_max) # print 'Saving green image.' # gim.save('gtest.png') rfti = FitsToImage(rFits) if not auto or rmax: rfti.scale_data(rmax) rim = rfti.get_image() print 'Red scale max =\t\t' + str(rfti.scale_max) # print 'Saving red image.' # rim.save('rtest.png') rgbim = Image.merge('RGB',(rim,gim,bim)) print 'Saving RGB image.' rgbim.save('rgbtest.png')
def encode(data, im): # Check whether the image is large enough. if im.size[0] < 32: print "Image should be at least 32 pixels wide." return None datasize = len(data) imsize = im.size[0]*(im.size[1]-1) if imsize < datasize*8: # ÞETTA ER EKKI NÓG! print "Image is not large enough." return None # Actual work. bands = im.split() blue = bands[2].load() # First line of pixels contains the size of the data in the first 32 pixels. width = im.size[0] bytes_per_row = width/8 wholerows = datasize/bytes_per_row lastrow = datasize%bytes_per_row a = [wholerows&255, (wholerows/256)&255, lastrow&255, (lastrow/256)&255] __embed(a, blue, 0) for i in range(wholerows): __embed(data[i*bytes_per_row:(i+1)*bytes_per_row], blue, i+1) __embed(data[wholerows*bytes_per_row:wholerows*bytes_per_row+lastrow], \ blue, wholerows+1) return Image.merge(im.mode, bands)
def make(self, sample=10, scale=1, percentage=0, filename_addition='_halftoned', angles=[0,15,30,45], style='color', antialias=False): """ Leave filename_addition empty to save the image in place. Arguments: sample: Sample box size from original image, in pixels. scale: Max output dot diameter is sample * scale (which is also the number of possible dot sizes) percentage: How much of the gray component to remove from the CMY channels and put in the K channel. filename_addition: What to add to the filename (before the extension). angles: A list of 4 angles that each screen channel should be rotated by. style: 'color' or 'grayscale'. antialias: boolean. """ f, e = os.path.splitext(self.path) outfile = "%s%s%s" % (f, filename_addition, e) try: im = Image.open(self.path) except IOError: raise if style == 'grayscale': angles = angles[:1] gray_im = im.convert('L') dots = self.halftone(im, gray_im, sample, scale, angles, antialias) new = dots[0] else: cmyk = self.gcr(im, percentage) dots = self.halftone(im, cmyk, sample, scale, angles, antialias) new = Image.merge('CMYK', dots) new.save(outfile)
def make(self, sample=10, scale=1, percentage=0, filename_addition='', angles=[0, 15, 30, 45]): """ Leave filename_addition empty to save the image in place. Arguments: sample: Sample box size from original image, in pixels. scale: Max output dot diameter is sample * scale (which is also the number of possible dot sizes) percentage: How much of the gray component to remove from the CMY channels and put in the K channel. filename_addition: What to add to the filename (before the extension). angles: A list of 4 angles that each screen channel should be rotated by. """ f, e = os.path.splitext(self.path) outfile = "%s%s%s" % (f, filename_addition, e) try: im = Image.open(self.path) except IOError: print "Cannot open ", self.path cmyk = self.gcr(im, percentage) dots = self.halftone(im, cmyk, sample, scale, angles) new = Image.merge('CMYK', dots) new.save(outfile)
def Cmyk(self, Button): self.p = Image.open(self.Newpath) self.p = self.p.convert("CMYK") c, m, y, k = self.p.split() self.s = Image.merge("CMYK", (m, y, c, k)) self.s.show() self.s.save(self.Newpath)
def Rgba(self, Button): self.p = Image.open(self.Newpath) self.p = self.p.convert("RGBA") r, g, b, a = self.p.split() self.s = Image.merge("RGBA", (b, r, g, a)) self.s.show() self.s.save(self.Newpath)
def raytrace(O, D, scene, bounce = 0): # O is the ray origin, D is the normalized ray direction # scene is a list of Sphere objects (see below) # bounce is the number of the bounce, starting at zero for camera rays distances = [s.intersect(O, D) for s in scene] nearest = reduce(np.minimum, distances) color = rgb(0, 0, 0) for (s, d) in zip(scene, distances): cc = s.light(O, D, d, scene, bounce) * (nearest != FARAWAY) * (d == nearest) color += cc _rgb = [Image.fromarray((255 * np.clip(c, 0, 1).reshape((h, w))).astype(np.uint8), "L") for c in cc.components()] global gen Image.merge("RGB", _rgb).save("p%02d.png" % gen) gen += 1 return color
def main(): im = Image.open("tree.jpg") cmyk = gcr(im, 0) dots = halftone(im, cmyk, 10, 1) im.show() new = Image.merge('CMYK', dots) new.show()
def image_to_string(image, lang=None, boxes=False, config=None): if len(image.split()) == 4: # In case we have 4 channels, lets discard the Alpha. # Kind of a hack, should fix in the future some time. r, g, b, a = image.split() image = Image.merge("RGB", (r, g, b)) input_file_name = '%s.bmp' % tempnam() output_file_name_base = tempnam() if not boxes: output_file_name = '%s.txt' % output_file_name_base else: output_file_name = '%s.box' % output_file_name_base try: image.save(input_file_name) status, error_string = run_tesseract(input_file_name, output_file_name_base, lang=lang, boxes=boxes, config=config) if status: errors = get_errors(error_string) raise TesseractError(status, errors) f = open(output_file_name) try: print(output_file_name) return f.read().strip() finally: f.close() finally: cleanup(input_file_name) cleanup(output_file_name)
def main(exrfile, jpgfile): file = OpenEXR.InputFile(exrfile) pt = Imath.PixelType(Imath.PixelType.FLOAT) dw = file.header()['dataWindow'] size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1) rgbf = [Image.fromstring("F", size, file.channel(c, pt)) for c in "RGB"] extrema = [im.getextrema() for im in rgbf] darkest = min([lo for (lo,hi) in extrema]) lighest = max([hi for (lo,hi) in extrema]) scale = 255 / (lighest - darkest) def normalize_0_255(v): return (v * scale) + darkest rgb8 = [im.point(normalize_0_255).convert("L") for im in rgbf] Image.merge("RGB", rgb8).save(jpgfile)
def image_tint(src, tint='#ffffff'): if Image.isStringType(src): # file path? src = Image.open(src) if src.mode not in ['RGB', 'RGBA']: raise TypeError('Unsupported source image mode: {}'.format(src.mode)) src.load() tr, tg, tb = getrgb(tint) tl = getcolor(tint, "L") # tint color's overall luminosity if not tl: tl = 1 # avoid division by zero tl = float(tl) # compute luminosity preserving tint factors sr, sg, sb = map(lambda tv: tv / tl, (tr, tg, tb)) # per component adjustments # create look-up tables to map luminosity to adjusted tint # (using floating-point math only to compute table) luts = (map(lambda lr: int(lr * sr + 0.5), range(256)) + map(lambda lg: int(lg * sg + 0.5), range(256)) + map(lambda lb: int(lb * sb + 0.5), range(256))) l = grayscale(src) # 8-bit luminosity version of whole image if Image.getmodebands(src.mode) < 4: merge_args = (src.mode, (l, l, l)) # for RGB verion of grayscale else: # include copy of src image's alpha layer a = Image.new("L", src.size) a.putdata(src.getdata(3)) merge_args = (src.mode, (l, l, l, a)) # for RGBA verion of grayscale luts += range(256) # for 1:1 mapping of copied alpha values return Image.merge(*merge_args).point(luts)
def write_to_image(path, text): x1, x2, x3, y1, y2, y3 = [4, 5, 3, 3, 5, 4] index = 0 D = 5 img = Image.open(path) img.getdata() bitext = text_to_binary(text) bitext = bitext + '0000000000000000' r, g, b = [np.array(x) for x in img.split()] lx, ly = r.shape() for x in xrange(0, lx - 2, 8): for y in xrange(0, ly - 2, 8): if index == len(bitext) - 1: break metric = r[x:x + 8, y:y + 8].astype('float') metric = dct(metric, norm='ortho') if bitext[index] == 1: metric[x1, y1] = max(metric[x1, y1], metric[x3, y3] + D + 1) metric[x2, y2] = max(metric[x2, y2], metric[x3, y3] + D + 1) else: metric[x1, y1] = min(metric[x1, y1], metric[x3, y3] - D - 1) metric[x2, y2] = min(metric[x2, y2], metric[x3, y3] - D - 1) index = index + 1 metric = idct(metric, norm='ortho') r[x:x + 8, y:y + 8] = metric.astype('uint8') im = Image.merge("RGB", [Image.fromarray(x) for x in [r, g, b]]) im.save('%s_writed' % path)
def __init__(self,rMapArray,gMapArray,bMapArray): """Each matrix must be the same size, with values in the range 0.0 to 1.0.""" rImage = self._arrayToImage(rMapArray) gImage = self._arrayToImage(gMapArray) bImage = self._arrayToImage(bMapArray) super(RGBBitmap,self).__init__(Image.merge('RGB',(rImage,gImage,bImage)))
def recog(self, template, data, expected=""): try: data_to_file = StringIO.StringIO(data) except: print "not valid image? %s" % data return "" if template == "360": learn_file = 'dod' else: learn_file = 'eng' img = Image.open(data_to_file) img.load() if len(img.split()) == 4: r, g, b, a = img.split() #re-organize the bands of this img for giving out a img fit for orc img = Image.merge("RGB", (b, g, b)) #print 'splited' #img.save("example.bmp", "BMP") price = image_to_string(img, True, learn_file) #print price #there is two \n in the output of tesseract price = re.sub(r'\n', '', price) #some times there will be spaces in the output price = re.sub(r' ', '', price) if re.match(r'^Y[1-9][0-9]*\.[0-9]{2}$', price): return (price, '', 1.0) else: #print "back up" sys.path.append('/'.join(os.getcwd().split('/')[:-1])) from recog import recog #from recog import recog #import recog bak_reader = recog.ImageRecer() bak_reader.study(os.getcwd() + '/recog/data/') return bak_reader.recog('360', data)
def xtest_image_pan(self): cam = camera.Camera((1.0, 1.0, 89.23, 320., 320., 240.0)) vo = VisualOdometer(cam) prev_af = None pose = None im = Image.open("img1.pgm") for x in [0, 5]: # range(0,100,10) + list(reversed(range(0, 100, 10))): lf = im.crop((x, 0, x + 640, 480)) rf = im.crop((x, 0, x + 640, 480)) af = SparseStereoFrame(lf, rf) if prev_af: pairs = vo.temporal_match(prev_af, af) pose = vo.solve(prev_af.kp, af.kp, pairs) for i in range(10): old = prev_af.kp[pairs[i][0]] new = af.kp[pairs[i][1]] print old, new, new[0] - old[0] prev_af = af print "frame", x, "has", len(af.kp), "keypoints", pose if 0: scribble = Image.merge("RGB", (lf, rf, Image.new("L", lf.size))).resize( (1280, 960)) #scribble = Image.merge("RGB", (Image.fromstring("L", lf.size, af0.lgrad),Image.fromstring("L", lf.size, af0.rgrad),Image.new("L", lf.size))).resize((1280,960)) draw = ImageDraw.Draw(scribble) for (x, y, d) in af0.kp: draw.line([(2 * x, 2 * y), (2 * x - 2 * d, 2 * y)], fill=(255, 255, 255)) for (x, y, d) in af1.kp: draw.line([(2 * x, 2 * y + 1), (2 * x - 2 * d, 2 * y + 1)], fill=(0, 0, 255))
def fromCircles(self): if not self.indexed: for by in range(4): for g in range(16): for bx in range(4): for r in range(16): b = bx + 4*by color = r + bx*16 + g*64 + by*1024 x = color%self.nims[0] y = color/self.nims[1] box = tuple((array([[x, y], [x+1, y+1]]) * self.submapsize).reshape(4)) sbox = array([[0, 0], self.submapsize]) cen = array(self.submapsize)/2 rr = r/16.; gg = g/16.; bb = b/16. ri = Image.new("L", tuple(self.submapsize)) gi = Image.new("L", tuple(self.submapsize)) bi = Image.new("L", tuple(self.submapsize)) rd = Draw(ri) gd = Draw(gi) bd = Draw(bi) rd.ellipse(tuple((rr*sbox + (1-rr)*cen).reshape(4,1)), 255) gd.ellipse(tuple((gg*sbox + (1-gg)*cen).reshape(4,1)), 255) bd.ellipse(tuple((bb*sbox + (1-bb)*cen).reshape(4,1)), 255) i = Image.merge("RGB", (ri, gi, bi)) self.mapim.paste(i, tuple(box))
def runCode(source, imgInput): if not source: print 'No source given.' return None rim, gim, bim = imgInput.split() ra, ga, ba = rim.load(), gim.load(), bim.load() # expose information dlocals = {} dlocals['imgInput'] = imgInput dlocals['width'] , dlocals['height'] = imgInput.size[0], imgInput.size[1] dlocals['ra'],dlocals['ga'],dlocals['ba'] = ra, ga, ba dlocals['rim'],dlocals['gim'],dlocals['bim'] = rim, gim, bim # I don't expect this to be used often #expose modules dlocals['Image'] = Image; dlocals['ImageChops'] = ImageChops; dlocals['ImageEnhance'] = ImageEnhance; dlocals['ImageFilter'] = ImageFilter; dlocals['ImageOps'] = ImageOps; if 'ImageDraw' in source: dlocals['ImageDraw'] = ImageDraw if 'ImageStat' in source: dlocals['ImageStat'] = ImageStat #run script code = compile(source, '<user-provided code>', 'exec') exec code in dlocals #recreate image if 'imgOutput' in dlocals: imgOutput = dlocals['imgOutput'] #evidently it was created manually else: imgOutput = Image.merge("RGB", (rim, gim, bim)) return imgOutput
def draw_circle(v): WIDTH = 640 HEIGHT = 640 R = 300 center = (WIDTH / 2, HEIGHT / 2) band_r = Image.new('L', (WIDTH, HEIGHT)) band_g = Image.new('L', (WIDTH, HEIGHT)) band_b = Image.new('L', (WIDTH, HEIGHT)) for y in range(HEIGHT): for x in range(WIDTH): tx, ty = x - center[0], y - center[1] d = math.sqrt(tx * tx + ty * ty) if d <= R: if d == 0: t = 0 else: if 0 <= ty: t = math.acos(tx / d) else: t = 2 * math.pi - math.acos(tx / d) r, g, b = hsv_to_rgb(t, d / R, v) band_r.putpixel((x,y), 255 * r) band_g.putpixel((x,y), 255 * g) band_b.putpixel((x,y), 255 * b) else: band_r.putpixel((x,y), 0) band_g.putpixel((x,y), 0) band_b.putpixel((x,y), 0) im = Image.merge('RGB', (band_r, band_g, band_b)) im.save('huecircle.png')
def make(src_path, out_path): src = Image.open(src_path) src = src.copy() (srcr, srcg, srcb, srca) = src.split() white = ImageChops.constant(src, 255) outr = cast_gradation(srcr, 0, 90) outg = cast_gradation(srcg, 0, 90) outb = cast_gradation(srcb, 0, 90) outa = srca.copy() outr = ImageChops.composite(srcr, white, srca) outg = ImageChops.composite(srcg, white, srca) outb = ImageChops.composite(srcb, white, srca) (shadow_a, shadow) = make_inset_shadow(srca) outr = ImageChops.subtract(outr, shadow, 1, 0) outg = ImageChops.subtract(outg, shadow, 1, 0) outb = ImageChops.subtract(outb, shadow, 1, 0) outa = ImageChops.lighter(outa, shadow_a) (highlight_a, highlight) = make_highlight(srca) outa = ImageChops.lighter(outa, highlight) outa = ImageChops.subtract(outa, ImageChops.constant(outa, 25), 1, 0) out = Image.merge('RGBA', (outr, outg, outb, outa)) out.save(out_path)
def _save_image(self, data, path): # Read and parse the given icon size icon_width = self.icon_size["width"] icon_height = self.icon_size["height"] # Create image from data with open(path, "w+b") as fd: try: img = Image.open(StringIO(data)) # Load the image right away so that we can access the image bands img.load() bands = img.split() # Prevent IOError: cannot write mode RGBA as BMP if len(bands) == 3: r, g, b = bands img = Image.merge("RGB", (r, g, b)) img.save(path) else: # Resize first by keeping the ratio, then convert to have alpha channel and then for to given size img.thumbnail((icon_width, icon_height), Image.ANTIALIAS) img = img.convert("RGBA") img = img.transform((icon_width, icon_height), Image.EXTENT, (0, 0, icon_width, icon_height)) img.save(path) except Exception, err: raise IOError("Failed to create image %s, skipping it (%s)" % (path, err))
def main(): if len(sys.argv) == 2: filename = sys.argv[1] try: image = Image.open(filename) image.load() if len(image.split()) == 4: # In case we have 4 channels, lets discard the Alpha. # Kind of a hack, should fix in the future some time. r, g, b, a = image.split() image = Image.merge("RGB", (r, g, b)) except IOError: sys.stderr.write('ERROR: Could not open file "%s"\n' % filename) exit(1) s = image_to_string(image) s1 = ''.join(e for e in s if e.isalnum()) s2 = ''.join([i for i in s1 if not i.isdigit()]) print(s2) elif len(sys.argv) == 4 and sys.argv[1] == '-l': lang = sys.argv[2] filename = sys.argv[3] try: image = Image.open(filename) image.load() except IOError: sys.stderr.write('ERROR: Could not open file "%s"\n' % filename) exit(1) print(image_to_string(image, lang=lang)) else: sys.stderr.write( 'Usage: python SCRBBL_plate.py [-l language] input_file\n') exit(2)
def launchCPU(self): frames_PIL = [ Image.fromstring("RGB", self.pre_video.getSize(), i.tostring()) for i in self.pre_video.getAllFrames() ] for i in xrange(1, len(frames_PIL)): # Diferencia diferencia = DifferenceFilter(frames_PIL[i], frames_PIL[i + 1]) diferencia.Apply(Filter.CPU) tmp = diferencia.fetchResult() # Threshold threshold = ThresholdFilter(tmp, level=20) threshold.Apply(Filter.CPU) tmp2 = threshold.fetchResult() # Erosion erosion = ErosionFilter(tmp2) erosion.Apply(Filter.CPU) post = erosion.fetchResult() # TODO Mergeado en una clase aparte r, g, b = frames_PIL[i + 1].split() tmp = ImageChops.add(r, post) merged = Image.merge("RGB", (tmp, g, b)) self.post_video.appendFrame(merged) print "#", # Terminado, salvamos resultado self.post_video.Save("./out.mpg")
def test_stereo(self): cam = camera.VidereCamera(open("wallcal.ini").read()) #lf = Image.open("wallcal-L.bmp").convert("L") #rf = Image.open("wallcal-R.bmp").convert("L") for offset in [ 1, 10, 10.25, 10.5, 10.75, 11, 63]: lf = Image.open("snap.png").convert("L") rf = Image.open("snap.png").convert("L") rf = rf.resize((16 * 640, 480)) rf = ImageChops.offset(rf, -int(offset * 16), 0) rf = rf.resize((640,480), Image.ANTIALIAS) for gradient in [ False, True ]: af = SparseStereoFrame(lf, rf, gradient) vo = VisualOdometer(cam) vo.find_keypoints(af) vo.find_disparities(af) error = offset - sum([d for (x,y,d) in af.kp]) / len(af.kp) self.assert_(abs(error) < 0.25) if 0: scribble = Image.merge("RGB", (lf,rf,Image.new("L", lf.size))).resize((1280,960)) #scribble = Image.merge("RGB", (Image.fromstring("L", lf.size, af0.lgrad),Image.fromstring("L", lf.size, af0.rgrad),Image.new("L", lf.size))).resize((1280,960)) draw = ImageDraw.Draw(scribble) for (x,y,d) in af0.kp: draw.line([ (2*x,2*y), (2*x-2*d,2*y) ], fill = (255,255,255)) for (x,y,d) in af1.kp: draw.line([ (2*x,2*y+1), (2*x-2*d,2*y+1) ], fill = (0,0,255))
def changeColours(canvas, redSlider, blueSlider, \ greenSlider, histWindow, histCanvas, previousRGB): if canvas.data.histWindowClose == True: histWindow.destroy() canvas.data.histWindowClose = False else: # the slider value indicates the % by which the red/green/blue # value of the pixels of the image need to incresed (for +ve values) # or decreased (for -ve values) if canvas.data.image != None and histWindow.winfo_exists(): R, G, B = canvas.data.image.split() sliderValR = redSlider.get() (previousR, previousG, previousB) = previousRGB scaleR = (sliderValR - previousR) / 100.0 R = R.point(lambda i: i + int(round(i * scaleR))) sliderValG = greenSlider.get() scaleG = (sliderValG - previousG) / 100.0 G = G.point(lambda i: i + int(round(i * scaleG))) sliderValB = blueSlider.get() scaleB = (sliderValB - previousB) / 100.0 B = B.point(lambda i: i + int(round(i * scaleB))) canvas.data.image = Image.merge(canvas.data.image.mode, (R, G, B)) canvas.data.imageForTk = makeImageForTk(canvas) drawImage(canvas) displayHistogram(canvas, histWindow, histCanvas) previousRGB = (sliderValR, sliderValG, sliderValB) canvas.after(200, lambda: changeColours(canvas, redSlider,\ blueSlider, greenSlider, histWindow, histCanvas, previousRGB))
def getPygImage(self, th = False, color = 0): img = self.getImage() w = self.width h = self.height if False == th: m = self.mode d = img.tostring() p = self.pitch else: th = 255.0 * th r, g, b = img.split() if 0 == color: r = Image.eval(r, lambda i: 255 if i < th else 0) g = Image.eval(g, lambda i: 255 if i > th else 0) b = Image.eval(b, lambda i: 255 if i > th else 0) elif 1 == color: r = Image.eval(r, lambda i: 255 if i > th else 0) g = Image.eval(g, lambda i: 255 if i < th else 0) b = Image.eval(b, lambda i: 255 if i > th else 0) else: r = Image.eval(r, lambda i: 255 if i > th else 0) g = Image.eval(g, lambda i: 255 if i > th else 0) b = Image.eval(b, lambda i: 255 if i < th else 0) m = img.mode i = Image.merge(m, (r, g, b)) d = i.tostring() p = -1 * w * len(m) return pyglet.image.ImageData(w, h, m, d, p)
def rgbColorFinder(rgbImg, colormin=(0, 0, 0), colormax=(255, 255, 255), allbands=1, rmode='1'): '''analyzes an RGB image, returns an image of the same size where each pixel is WHITE if the pixel in rgbImage MATCHES the color range colormin-to-colormax, or BLACK if the pixel in rgbImage DOES NOT MATCH the color range. a pixel is MATCHES the color range if allbands!=0 and if for EVERY color pixel[i], colormin[i]<=pixel[i] and pixel[i]<=colormax[i], or if allbands==0 and if for ANY color pixel[i], colormin[i]<=pixel[i] and pixel[i]<=colormax[i]. rmode determines the mode of the returned image ("1", "L" or "RGB") jjk 12/11/02''' inbands = rgbImg.split() outbands = [] for srcband, cmin, cmax in zip(inbands, colormin, colormax): outbands.append( srcband.point( lambda v1, v2=cmin, v3=cmax: v2 <= v1 and v1 <= v3 and 255)) if allbands == 0: tband = ImageChops.lighter( ImageChops.lighter(outbands[0], outbands[1]), outbands[2]) else: tband = ImageChops.darker(ImageChops.darker(outbands[0], outbands[1]), outbands[2]) if rmode == 'L': return tband elif rmode == 'RGB': return Image.merge('RGB', (tband, tband, tband)) # 'RGB' else: # rmode=='1' return tband.convert('1')
def _remove_alpha(file_in, file_out): """ all pic files should have no alpha channel before OCR """ img = Image.open(file_in) if img.split() == 4: rgba = img.split() img = Image.merge("RGB", rgba[:3]) img.save(file_out)
def index(req, img = None): session = Session.Session(req) if req.headers_in.has_key('content-length'): if int(req.headers_in['content-length'])> 2097152: return 'Error: Max file size is 2MB.' try: image = Image.open(img.file) image_type = image.format except: return 'Error: Could not open file.' if image_type != 'JPEG' and image_type != 'PNG' and image_type != 'BMP': return 'Error: Wrong file format.' else: # prevent IOError: cannot write mode RGBA as BMP image.load() if len(image.split()) == 4: r, g, b, a = image.split() image = Image.merge("RGB", (r, g, b)) image.thumbnail((max_image_size,max_image_size)) raw_image = StringIO.StringIO() image.save(raw_image, 'BMP') session['raw_image'] = raw_image session.save() return "OK"
def execute(self): import Image import ImageOps i = Image.open(self.target) i = i.convert("RGB") if getattr(self, 'brightness', None): i = i.point(lambda p: p * self.brightness) r, g, b = i.split() a = { 'r': r, 'g': g, 'b': b, 'x': Image.new("L", r.size, color=0), }.get(self.level) if not a: a = Image.new("L", r.size, color=self.level) if self.level == 'x': pxi = i.load() pxa = a.load() for y in xrange(a.size[1]): for x in xrange(a.size[0]): p = pxi[x, y] pxa[x, y] = int((p[0] + p[1] + p[2]) / 3.0) if getattr(self, 'invert_alpha', None): a = ImageOps.invert(a) i2 = Image.merge("RGBA", (r, g, b, a)) i2.save(self.target) """
def __init__(self,hue,sat,val): """Each matrix must be the same size, with values in the range 0.0 to 1.0.""" shape = hue.shape # Assumed same as sat.shape and val.shape rmat = Numeric.zeros(shape,Numeric.Float) gmat = Numeric.zeros(shape,Numeric.Float) bmat = Numeric.zeros(shape,Numeric.Float) # Note: should someday file a feature request for PIL for them # to accept an image of type 'HSV', so that they will do this # conversion themselves, without us needing an explicit loop # here. That should speed this up. ch = hue.clip(0.0,1.0) cs = sat.clip(0.0,1.0) cv = val.clip(0.0,1.0) for i in range(shape[0]): for j in range(shape[1]): r,g,b = hsv_to_rgb(ch[i,j],cs[i,j],cv[i,j]) rmat[i,j] = r gmat[i,j] = g bmat[i,j] = b rImage = self._arrayToImage(rmat) gImage = self._arrayToImage(gmat) bImage = self._arrayToImage(bmat) super(HSVBitmap,self).__init__(Image.merge('RGB',(rImage,gImage,bImage)))
def main(): if len(sys.argv) == 2: filename = sys.argv[1] try: image = Image.open(filename) if len(image.split()) == 4: # In case we have 4 channels, lets discard the Alpha. # Kind of a hack, should fix in the future some time. r, g, b, a = image.split() image = Image.merge("RGB", (r, g, b)) except IOError: sys.stderr.write('ERROR: Could not open file "%s"\n' % filename) exit(1) print(image_to_string(image)) elif len(sys.argv) == 4 and sys.argv[1] == '-l': lang = sys.argv[2] filename = sys.argv[3] try: image = Image.open(filename) except IOError: sys.stderr.write('ERROR: Could not open file "%s"\n' % filename) exit(1) print(image_to_string(image, lang=lang)) else: sys.stderr.write('Usage: python pytesseract.py [-l lang] input_file\n') exit(2)
def tint(self, tint='#ffffff'): self.open() src = self.img if src.mode not in ['RGB', 'RGBA']: raise TypeError('Unsupported source image mode: {}'.format(src.mode)) src.load() if type(tint) in [str, unicode]: tr, tg, tb = getrgb(tint) tl = getcolor(tint, "L") # tint color's overall luminosity else: tr, tg, tb = tint tl = sum([tr,tg,tb])/3 if not tl: tl = 1 # avoid division by zero tl = float(tl) # compute luminosity preserving tint factors sr, sg, sb = map(lambda tv: tv/tl, (tr, tg, tb)) # per component adjustments # create look-up tables to map luminosity to adjusted tint # (using floating-point math only to compute table) luts = (map(lambda lr: int(lr*sr + 0.5), range(256)) + map(lambda lg: int(lg*sg + 0.5), range(256)) + map(lambda lb: int(lb*sb + 0.5), range(256))) l = grayscale(src) # 8-bit luminosity version of whole image if Image.getmodebands(src.mode) < 4: merge_args = (src.mode, (l, l, l)) # for RGB verion of grayscale else: # include copy of src image's alpha layer a = Image.new("L", src.size) a.putdata(src.getdata(3)) merge_args = (src.mode, (l, l, l, a)) # for RGBA verion of grayscale luts += range(256) # for 1:1 mapping of copied alpha values self.img = Image.merge(*merge_args).point(luts) self.save() self.close()
def __init__(self, hue, sat, val): """Each matrix must be the same size, with values in the range 0.0 to 1.0.""" shape = hue.shape # Assumed same as sat.shape and val.shape rmat = np.zeros(shape, dtype=np.float) gmat = np.zeros(shape, dtype=np.float) bmat = np.zeros(shape, dtype=np.float) # Note: should someday file a feature request for PIL for them # to accept an image of type 'HSV', so that they will do this # conversion themselves, without us needing an explicit loop # here. That should speed this up. ch = hue.clip(0.0, 1.0) cs = sat.clip(0.0, 1.0) cv = val.clip(0.0, 1.0) for i in range(shape[0]): for j in range(shape[1]): r, g, b = hsv_to_rgb(ch[i, j], cs[i, j], cv[i, j]) rmat[i, j] = r gmat[i, j] = g bmat[i, j] = b rImage = self._arrayToImage(rmat) gImage = self._arrayToImage(gmat) bImage = self._arrayToImage(bmat) super(HSVBitmap, self).__init__(Image.merge('RGB', (rImage, gImage, bImage)))
def _save_image(self, data, path): # Read and parse the given icon size icon_width = self.icon_size['width'] icon_height = self.icon_size['height'] # Create image from data with open(path, 'w+b') as fd: try: img = Image.open(StringIO(data)) # Load the image right away so that we can access the image bands img.load() bands = img.split() # Prevent IOError: cannot write mode RGBA as BMP if len(bands) == 3: r, g, b = bands img = Image.merge("RGB", (r, g, b)) img.save(path) else: # Resize first by keeping the ratio, then convert to have alpha channel and then for to given size img.thumbnail((icon_width, icon_height), Image.ANTIALIAS) img = img.convert("RGBA") img = img.transform((icon_width, icon_height), Image.EXTENT, (0, 0, icon_width, icon_height)) img.save(path) except Exception, err: raise IOError('Failed to create image %s, skipping it (%s)' % (path, err))
def __init__( self, image=None, # PIL image size=None, ctx=None, imageType=None, # determines file type fileName=None, # if set determines output file name ): """ Canvas can be used in four modes: 1) using the supplied PIL image 2) using the supplied cairo context ctx 3) writing to a file fileName with image type imageType 4) creating a cairo surface and context within the constructor """ self.image = None self.imageType = imageType if image is not None: try: imgd = image.tostring("raw", "BGRA") except SystemError: r, g, b, a = image.split() imgd = Image.merge("RGBA", (b, g, r, a)).tostring("raw", "RGBA") a = array.array('B', imgd) stride = image.size[0] * 4 surface = cairo.ImageSurface.create_for_data( a, cairo.FORMAT_ARGB32, image.size[0], image.size[1], stride) ctx = cairo.Context(surface) size = image.size[0], image.size[1] self.image = image elif ctx is None and size is not None: if cairo.HAS_PDF_SURFACE and imageType == "pdf": surface = cairo.PDFSurface(fileName, size[0], size[1]) elif cairo.HAS_SVG_SURFACE and imageType == "svg": surface = cairo.SVGSurface(fileName, size[0], size[1]) elif cairo.HAS_PS_SURFACE and imageType == "ps": surface = cairo.PSSurface(fileName, size[0], size[1]) elif imageType == "png": surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size[0], size[1]) else: raise ValueError( "Unrecognized file type. Valid choices are pdf, svg, ps, and png" ) ctx = cairo.Context(surface) ctx.set_source_rgb(1, 1, 1) ctx.paint() else: surface = ctx.get_target() if size is None: try: size = surface.get_width(), surface.get_height() except AttributeError: size = None self.ctx = ctx self.size = size self.surface = surface self.fileName = fileName
def main(): if len(sys.argv) == 2: filename = sys.argv[1] try: image = Image.open(filename) if len(image.split()) == 4: # In case we have 4 channels, lets discard the Alpha. # Kind of a hack, should fix in the future some time. r, g, b, a = image.split() image = Image.merge("RGB", (r, g, b)) except IOError: sys.stderr.write('ERROR: Could not open file "%s"\n' % filename) exit(1) print(image_to_string(image)) elif len(sys.argv) == 4 and sys.argv[1] == '-l': lang = sys.argv[2] filename = sys.argv[3] try: image = Image.open(filename) except IOError: sys.stderr.write('ERROR: Could not open file "%s"\n' % filename) exit(1) print(image_to_string(image, lang=lang)) else: sys.stderr.write('Usage: python tesseract.py [-l language] input_file\n') exit(2)
def make(self, sample=10, scale=1, percentage=0, filename_addition='', angles=None): """ Leave filename_addition empty to save the image in place. Arguments: sample: Sample box size from original image, in pixels. scale: Max output dot diameter is sample * scale (which is also the number of possible dot sizes) percentage: How much of the gray component to remove from the CMY channels and put in the K channel. filename_addition: What to add to the filename (before the extension). angles: A list of 4 angles that each screen channel should be rotated by. """ f, e = os.path.splitext(self.path) outfile = "%s%s%s" % (f, filename_addition, e) try: im = Image.open(self.path) except IOError: print "Cannot open ", self.path if not angles: angles = self.default_angles cmyk = self.gcr(im, percentage) dots = self.halftone(im, percentage, cmyk, sample, scale, angles) new = Image.merge('CMYK', dots) new = new.resize(im.size, Image.ANTIALIAS) new.save(outfile)
def loadImage(srcName, res): im = Image.open(getSrcPath(srcName, res)) if srcName == 'actions/edit_remove': r, g, b, a = im.split() im = Image.merge('RGBA', (g, r, b, a)) im = im.point(lambda x: 1.5 * x) return im
def launchCPU(self): frames_PIL = [Image.fromstring("RGB", self.pre_video.getSize(), i.tostring()) for i in self.pre_video.getAllFrames()] for i in xrange(1, len(frames_PIL)): # Diferencia diferencia = DifferenceFilter(frames_PIL[i], frames_PIL[i + 1]) diferencia.Apply(Filter.CPU) tmp = diferencia.fetchResult() # Threshold threshold = ThresholdFilter(tmp, level=20) threshold.Apply(Filter.CPU) tmp2 = threshold.fetchResult() # Erosion erosion = ErosionFilter(tmp2) erosion.Apply(Filter.CPU) post = erosion.fetchResult() # TODO Mergeado en una clase aparte r, g, b = frames_PIL[i + 1].split() tmp = ImageChops.add(r, post) merged = Image.merge("RGB", (tmp, g, b)) self.post_video.appendFrame(merged) print "#", # Terminado, salvamos resultado self.post_video.Save("./out.mpg")
def shift_color_mode(img,mode): """ Shifts color mode to either HSV, HLS or YIQ and returns an Image.Image object """ if mode is 'HSV': convert = colorsys.rgb_to_hsv elif mode is 'HLS': convert = colorsys.rgb_to_hls elif mode is 'YIQ': convert = colorsys.rgb_to_yiq else: raise Exception('Bad mode') if isinstance(img,Image.Image): r,g,b = img.split() A = [] B = [] C = [] for rd,gn,bl in zip(r.getdata(),g.getdata(),b.getdata()) : h,l,s = convert(rd/255.,gn/255.,bl/255.) A.append(int(h*255.)) B.append(int(l*255.)) C.append(int(s*255.)) r.putdata(A) g.putdata(B) b.putdata(C) return Image.merge('RGB',(r,g,b)) else: raise Exception('Not an Image object') return None
def callback_button_1(): # Adjust red intensity by slider value. out_red = source[R].point(lambda i: i * red_frac) out_green = source[G].point(lambda i: i * green_frac) # Adjust green out_blue = source[B].point(lambda i: i * blue_frac) # Adjust blue new_source = [out_red, out_green, out_blue] im_2 = Image.merge(im_1.mode, new_source) # Re-compine bands im_2.show()
def __call__(self, img): if self.mode == 'BGR': img = img.convert('RGB') r, g, b = img.split() img = Image.merge('RGB', (b, g, r)) return img else: return img.convert(self.mode)
def img_img(f0, f1, RT): (ok, f1p, f1i0, f1i) = img_err(f0, f1, RT) c_r = 255 * vop.where(ok, f1i, 0) c_g = 255 * vop.where(ok, f1i0, 0) c_b = 0 * c_g # 255 * vop.where(ok & (abs(f1d0 - f0d) < 1.5), 1.0, 0.0) return Image.merge("RGB", [ Image.fromstring("L", chipsize, c.tostring()) for c in [c_r, c_g, c_b] ])
def __call__(self, img): if self.mode == "BGR": img = img.convert("RGB") r, g, b = img.split() img = Image.merge("RGB", (b, g, r)) return img else: return img.convert(self.mode)
def split2(im): im = im.convert('RGB') r, g, b = im.split() r = r.point(lambda i: i * 299 / 1000) g = g.point(lambda i: i * 578 / 1000) b = b.point(lambda i: i * 144 / 1000) tmp = Image.merge('RGB', (r, g, b)) tmp.show()
def split(im): im = im.convert('RGB') r, g, b = im.split() r.show() g.show() b.show() tmp = Image.merge('RGB', (b, g, r)) #将b,r两个通道进行翻转 tmp.show()
def LoadCompressed(data): JpegHeaderSize = ReadUInt32(data, _BLP_HEADER_SIZE) Offset, Size = MipMap(data, 0) parser = ImageFile.Parser() parser.feed(data[_BLP_HEADER_SIZE+4:_BLP_HEADER_SIZE+4+JpegHeaderSize]) parser.feed(data[Offset:Offset+Size]) img = parser.close().convert('RGB') r, g, b = img.split() return Image.merge("RGB", (b, g, r))
def asImage(self): # findBlocks is going to modify the pic in place #if hasattr(self, 'pilImage'): # return self.pilImage self.pilImage = Image.fromstring("RGB", (self.w, self.h), self.string) b, g, r = self.pilImage.split() self.pilImage = Image.merge("RGB", (r, g, b)) return self.pilImage