def image_diff(im1, im2): """Return the diff of two images""" from PIL from PIL import Image, ImageMath r1, g1, b1, a1 = im1.convert('RGBA').split() r2, g2, b2, a2 = im2.convert('RGBA').split() diff_image = ImageMath.eval( """convert( max( max( max(abs(r1 - r2), abs(g1 - g2)), abs(b1 - b2) ), abs(a1 - a2) ), 'L')""", r1=r1, r2=r2, g1=g1, g2=g2, b1=b1, b2=b2, a1=a1, a2=a2) if ImageMath.eval('not(image)', image=diff_image): return return diff_image
def main(args): coverImg = open_image(args.cover_image, "rb") # read only in binary secretImg = open_image(args.secret_image, "rb") # check the size, for now just make secret image size equals cover image secretImg = secretImg.resize(coverImg.size) red, green, blue = coverImg.split() sred, sgreen, sblue = secretImg.split() red2 = ImageMath.eval("convert(a&0xFE|b&0x1,'L')", a=red, b=sred) green2 = ImageMath.eval("convert(a&0xFE|b&0x1,'L')", a=green, b=sgreen) blue2 = ImageMath.eval("convert(a&0xFE|b&0x1,'L')", a=blue, b=sblue) out = Image.merge("RGB", (red2, green2, blue2)) out.save("merged.bmp") exit(0)
def paint(self, image): if self.bpp != 0: width = self.lcd_size[0] height = self.lcd_size[1] if self.bpp == 1: # Paint to 565 image provided into an ARGB image surface for PIL's benefit. PIL doesn't support 565? argb_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) argb_context = cairo.Context(argb_surface) argb_context.set_source_surface(image) argb_context.paint() # Now convert the ARGB to a PIL image so it can be converted to a 1 bit monochrome image, with all # colours dithered. It would be nice if Cairo could do this :( Any suggestions? pil_img = Image.frombuffer("RGBA", self.lcd_size, argb_surface.get_data(), "raw", "RGBA", 0, 1) pil_img = ImageMath.eval("convert(pil_img,'1')",pil_img=pil_img) pil_img = ImageMath.eval("convert(pil_img,'P')",pil_img=pil_img) pil_img = pil_img.point(lambda i: i >= 250,'1') invert_control = self.get_control("invert_lcd") if invert_control and invert_control.value == 1: pil_img = pil_img.point(lambda i: 1^i) # Create drawable message pil_img = pil_img.convert("RGB") self.image = pil_img else: # Take a copy of the image to prevent flickering argb_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) argb_context = cairo.Context(argb_surface) argb_context.set_source_surface(image) argb_context.paint() self.image = argb_surface gobject.timeout_add(0, self.redraw)
def put_highlight(image, highlight, resample_highlight, opacity, cache=None): if cache is None: cache = {} resample_highlight = getattr(Image, resample_highlight) id = 'highlight_%s_w%d_h%d_o%d'\ % (highlight, image.size[0], image.size[1], opacity) try: highlight = cache[id] except KeyError: highlight = open_image(highlight)\ .convert('RGBA').resize(image.size, resample_highlight) if opacity < 100: #apply opacity highlight_alpha = imtools.get_alpha(highlight) opacity = (255 * opacity) / 100 highlight.putalpha(ImageMath.eval("convert((a * o) / 255, 'L')", a=highlight_alpha, o=opacity)) #store in cache cache[id] = highlight if not has_transparency(image): image = image.convert('RGBA') else: if has_transparency(image): image = image.convert('RGBA') alpha = imtools.get_alpha(image) highlight = highlight.copy() highlight_alpha = imtools.get_alpha(highlight) highlight.putalpha(ImageMath.eval("convert(min(a, b), 'L')", a=alpha, b=highlight_alpha)) overlay = highlight.convert('RGB') paste(image, overlay, mask=highlight) return image
def test_convert(self): self.assertEqual(pixel( ImageMath.eval("convert(A+B, 'L')", images)), "L 3") self.assertEqual(pixel( ImageMath.eval("convert(A+B, '1')", images)), "1 0") self.assertEqual(pixel( ImageMath.eval("convert(A+B, 'RGB')", images)), "RGB (3, 3, 3)")
def _lsb_pixel_decode(image): r, g, b, *_ = image.split() r = ImageMath.eval("convert(c&0x1, 'L')", c=r) g = ImageMath.eval("convert(c&0x1, 'L')", c=g) b = ImageMath.eval("convert(c&0x1, 'L')", c=b) data = roundrobin(iter_pixels(r), iter_pixels(g), iter_pixels(b)) return bytes([reduce(lambda byte, bit: byte << 1 | bit, eight_bits) for eight_bits in grouper(data, 8, fillvalue=0)])
def color_to_alpha(image, color=None): image = image.convert('RGBA') width, height = image.size color = map(float, color) img_bands = [band.convert("F") for band in image.split()] # Find the maximum difference rate between source and color. I had to use two # difference functions because ImageMath.eval only evaluates the expression # once. alpha = ImageMath.eval( """float( max( max( max( difference1(red_band, cred_band), difference1(green_band, cgreen_band) ), difference1(blue_band, cblue_band) ), max( max( difference2(red_band, cred_band), difference2(green_band, cgreen_band) ), difference2(blue_band, cblue_band) ) ) )""", difference1=difference1, difference2=difference2, red_band = img_bands[0], green_band = img_bands[1], blue_band = img_bands[2], cred_band = color[0], cgreen_band = color[1], cblue_band = color[2] ) # Calculate the new image colors after the removal of the selected color new_bands = [ ImageMath.eval( "convert((image - color) / alpha + color, 'L')", image = img_bands[i], color = color[i], alpha = alpha ) for i in xrange(3) ] # Add the new alpha band new_bands.append(ImageMath.eval( "convert(alpha_band * alpha, 'L')", alpha = alpha, alpha_band = img_bands[3] )) return Image.merge('RGBA', new_bands)
def getColorfulness(im): #OK """return (cf, sigma_rgyb, mu_rgyb)""" r, g, b = im.split() im_rg = ImageMath.eval("a - b", a=r, b=g) im_yb = ImageMath.eval("(a + b)/2 - c", a=r, b=g, c=b) rg = list(im_rg.getdata()) yb = list(im_yb.getdata()) sigma = math.sqrt(numpy.std(rg) ** 2 + numpy.std(yb) ** 2) mu = math.sqrt(numpy.average(rg) ** 2 + numpy.average(yb) ** 2) return sigma + 0.3 * mu
def normalizeImage(im): # split RGB images into 3 channels rr, gg, bb = im.split() rTmp = ImageMath.eval("int(a*((float(255/max(a,b)))))", a=rr, b=rr).convert('L') gTmp = ImageMath.eval("int(a*((float(255/max(a,b)))))", a=gg, b=gg).convert('L') bTmp = ImageMath.eval("int(a*((float(255/max(a,b)))))", a=bb, b=bb).convert('L') # merge channels into RGB image imgOut = Image.merge("RGB", (rTmp, gTmp, bTmp)) return imgOut
def applyOutline(a, o): w, h = a.size c = a.crop((o, o, w - o, h - o)) t = Image.new("L", a.size) for n in ((o, 0), (0, o), (o + o, o), (o, o + o)): t.paste(c, n) a = ImageMath.eval("convert(max(a,b),'L')", a=a, b=t) for n in ((0, 0), (o + o, 0), (0, o + o), (o + o, o + o)): t.paste(c, n) a = ImageMath.eval("convert(max(a,b/1.414),'L')", a=a, b=t) return a
def substractImage(imgA,imgB): rA, gA, bA = imgA.split() rB, gB, bB = imgB.split() rTmp = ImageMath.eval("a-b", a=rA, b=rB).convert('L') gTmp = ImageMath.eval("a-b", a=gA, b=gB).convert('L') bTmp = ImageMath.eval("a-b", a=bA, b=bB).convert('L') # merge channels into RGB image imgOut = Image.merge("RGB", (rTmp, gTmp, bTmp)) return imgOut
def divideImage(imgA,imgB): # split RGB images into 3 channels rA, gA, bA = imgA.split() rB, gB, bB = imgB.split() # divide each channel (image1/image2) rTmp = ImageMath.eval("int(a/((float(b))/256))", a=rA, b=rB).convert('L') gTmp = ImageMath.eval("int(a/((float(b))/256))", a=gA, b=gB).convert('L') bTmp = ImageMath.eval("int(a/((float(b))/256))", a=bA, b=bB).convert('L') # merge channels into RGB image imgOut = Image.merge("RGB", (rTmp, gTmp, bTmp)) return imgOut
def optim_obj_xor(x): draw(x) image = get_image() xor = imath.eval("a^b", a=image, b=image_obj) res = sum(xor.getdata()) print x, res return res
def encode_data(cover_rgb, secret_rgb, bits): encoded_rgb = [] for k in range(3): encoded_rgb.append(ImageMath.eval("convert((cover_rgb & (256 - 2**bits)) + ((secret_rgb & (256 - 2**(8 - bits)) - 1) >> 8 - bits), 'L')", cover_rgb = cover_rgb[k], secret_rgb = secret_rgb[k], bits = bits)) return tuple(encoded_rgb)
def segment(image_filepath, **kwargs): input_img = Image.open(image_filepath) # make a '1' bit image with the same size as the input_img mask_img = Image.new('1', input_img.size) # instantiate an ImageDraw object using the mask_img object mask_drawer = ImageDraw.Draw(mask_img) try: json_poly_data = json.loads(kwargs['JSON']) except ValueError: # There's a problem in the JSON - it may be malformed, or empty json_poly_data = [] for polygon in json_poly_data: flattened_poly = [j for i in polygon for j in i] mask_drawer.polygon(flattened_poly, outline=1, fill=1) output_img = ImageMath.eval('b - a', a=input_img, b=mask_img) output_img = ImageOps.invert(output_img.convert('RGB')) encoded = json.dumps(json_poly_data) return { 'tiff': output_img, 'json': encoded }
def run(self): while True: try: camera = WebCamera.objects.get(pk = self._camera.id) if camera.motion_control: now = datetime.now() request = get_pool().request("GET", "%s?action=snapshot" % camera.internal_url) try: source = Image.open(BytesIO(request.data)) img = ImageOps.equalize(ImageOps.grayscale(source)) if self._previous is not None: out = ImageMath.eval("convert(a - b, 'L')", a = img, b = self._previous) out = out.filter(MedianFilter()) total = 0 for idx, val in enumerate(out.histogram()): total += val * idx if total > 3000000: camera.last_motion = now camera.save() filename = os.path.join(camera.motion_folder, "{:%Y%m%d-%H%M%S}.jpg".format(now)) source.save(filename) filesize = os.path.getsize(filename) if filesize < 6700: os.remove(filename) self._previous = img finally: request.close() else: self._previous = None except: print("Ignore Exception") sleep(1)
def decode_data(rgb, bits): decoded_rgb = [] for k in range(3): decoded_rgb.append(ImageMath.eval("convert((rgb & 2**bits - 1) << 8 - bits, 'L')", rgb = rgb[k], bits = bits)) return tuple(decoded_rgb)
def warmup(image, midtone, brighten, amount=100): """Apply a toning filter. Move the midtones to the desired color while preserving blacks and whites with optional mixing with original image - amount: 0-100%""" mode = image.mode info = image.info if image.mode != "L": im = imtools.convert(image, "L") else: im = image if image.mode != "RGBA" and imtools.has_transparency(image): image = imtools.convert(image, "RGBA") luma = imtools.convert(imtools.split(im)[0], "F") o = [] m = ImageColor.getrgb(midtone) b = brighten / 600.0 # Calculate channels separately for l in range(3): o.append(ImageMath.eval("m*(255-i)*i+i", i=luma, m=4 * ((m[l] / 255.0) - 0.5 + b) / 255.0).convert("L")) colorized = Image.merge("RGB", tuple(o)) if imtools.has_alpha(image): imtools.put_alpha(colorized, imtools.get_alpha(image)) if amount < 100: colorized = imtools.blend(image, colorized, amount / 100.0) return colorized
def strip_processing(path, blur_radius=7, iter_steps=1, binarize_threshold=10): """Strip precessing function. Inputs: string: path of the image blur_radius: radius of gaussian blur iter_steps: execution times of denoise binarize_threshold: used as function lut's input Outputs: Image: the processed image.""" gray=ImageOps.invert(ImageOps.grayscale(Image.open("stripes.jpg"))) gray_blur=gray.filter(ImageFilter.GaussianBlur(blur_radius)) high_freq=ImageMath.eval("25*(a-b)",a=gray,b=gray_blur).convert("L") binarized=ImageOps.invert(high_freq.point(lut(binarize_threshold))).convert("1") binarized_data=binarized.load() #binarized.show() height=binarized.height width=binarized.width pix=np.array([[np.uint8(binarized_data[j,i]) for j in range(width)] for i in range(height)]) for i in range(iter_steps): pix=denoise(pix) answer=Image.fromarray(pix) #answer.show() #answer.save("test.bmp") return answer
def makeColorTransparent(image, color, thresh2=0): from PIL import ImageMath image = image.convert("RGBA") red, green, blue, alpha = image.split() image.putalpha(ImageMath.eval("""convert(((((t - d(c, (r, g, b))) >> 31) + 1) ^ 1) * a, 'L')""", t=thresh2, d=distance2, c=color, r=red, g=green, b=blue, a=alpha)) return image
def generate_animated_images_old(front_image, back_image, scale_factor): animated_images = [] for x in xrange (0, front_image.size[0], scale_factor): temp_image = Image.new('1', front_image.size, "white") temp_image.paste(front_image.crop((front_image.size[0] - x, 0, front_image.size[0], front_image.size[1])), (0,0)) animated_image = ImageMath.eval("convert((a & b), 'L')", a=temp_image, b=back_image) #animated_image.save(file_name + "_" + str(x) + file_ext) animated_images.append(animated_image) for x in xrange (0, front_image.size[0] + 1, scale_factor): temp_image = Image.new('1', front_image.size, "white") temp_image.paste(front_image.crop((0, 0, front_image.size[0] - x, front_image.size[1])), (x, 0)) animated_image = ImageMath.eval("convert((a & b), 'L')", a=temp_image, b=back_image) #animated_image.save(file_name + "_" + str(x+front_image.size[0]) + file_ext) animated_images.append(animated_image) return animated_images
def assert_image_similar(self, a, b, epsilon, msg=None): epsilon = float(epsilon) self.assertEqual( a.mode, b.mode, msg or "got mode %r, expected %r" % (a.mode, b.mode)) self.assertEqual( a.size, b.size, msg or "got size %r, expected %r" % (a.size, b.size)) a, b = convert_to_comparable(a, b) diff = 0 for ach, bch in zip(a.split(), b.split()): chdiff = ImageMath.eval("abs(a - b)", a=ach, b=bch).convert('L') diff += sum(i * num for i, num in enumerate(chdiff.histogram())) ave_diff = float(diff)/(a.size[0]*a.size[1]) try: self.assertGreaterEqual( epsilon, ave_diff, (msg or '') + " average pixel value difference %.4f > epsilon %.4f" % ( ave_diff, epsilon)) except Exception as e: if HAS_UPLOADER: try: url = test_image_results.upload(a, b) logger.error("Url for test images: %s" % url) except: pass raise e
def process(self, image): """ @param image -- The image to process. Returns a single image, or a list containing one or more images. """ BaseFilter.process(self, image) base, alpha = image.split() if self.scaleTowardCenter: scale = float(self.factor) assert base.mode == "L" maxValue = 255 # TODO: Determine how to get maximum value __allowed__. offset = ((1.0 - self.factor) / 2.0) * maxValue newImage = ImageMath.eval( "convert(convert(gray, 'F') * scale + offset, mode)", gray=base, scale=scale, offset=offset, mode=base.mode, ) else: contrastEnhancer = ImageEnhance.Contrast(image.split()[0]) newImage = contrastEnhancer.enhance(self.factor) newImage.putalpha(alpha) return newImage
def getContrast(im): #OK """return contrast""" im = im.convert('L') stat = ImageStat.Stat(im) mean = stat.mean[0] im_diff = ImageMath.eval("abs(a - b)", a=im, b=mean) diff = list(im_diff.getdata()) return math.sqrt(1.0 / (len(diff) - 1) * sum(pix ** 2 for pix in diff))
def xor_closure(target, path): ''' target shall be a single-band Image instance ''' target = imath.eval("x>>7", x=target) def _get_xor(image): xor_img = imath.eval("(a>>7)^b", a=image, b=target) return sum(xor_img.getdata()) return _get_xor
def paint(self, img): if not self.is_connected(): return # Just return if the device has no LCD if self.device.bpp == 0: return None self.lock.acquire() try : size = self.get_size() # Paint to 565 image provided into an ARGB image surface for PIL's benefit. PIL doesn't support 565? argb_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size[0], size[1]) argb_context = cairo.Context(argb_surface) argb_context.set_source_surface(img) argb_context.paint() # Now convert the ARGB to a PIL image so it can be converted to a 1 bit monochrome image, with all # colours dithered. It would be nice if Cairo could do this :( Any suggestions? pil_img = Image.frombuffer("RGBA", size, argb_surface.get_data(), "raw", "RGBA", 0, 1) pil_img = ImageMath.eval("convert(pil_img,'1')",pil_img=pil_img) pil_img = ImageMath.eval("convert(pil_img,'P')",pil_img=pil_img) pil_img = pil_img.point(lambda i: i >= 250,'1') invert_control = self.get_control("invert_lcd") if invert_control.value == 0: pil_img = pil_img.point(lambda i: 1^i) # Covert image buffer to string buf = "" for x in list(pil_img.getdata()): buf += chr(x) if len(buf) != self.device.lcd_size[0] * self.device.lcd_size[1]: logger.warning("Invalid buffer size") else: try : self.send(buf) except IOError as e: logger.error("Failed to send buffer.", exc_info = e) self.disconnect() finally: self.lock.release()
def _on_snapshot_clicked(self): img = self.optimizer.rendis.acquire().acquire_snapshot() filename = QFileDialog.getSaveFileName(self, "save the binary shadow snapshot", "../img/", "image file (*.png)") if filename != '': img = ImageMath.eval("a/127 * 255", a=img) img.save(str(filename), format='png') pass
def generate_animated_images(front_image, back_image, scale_factor): animated_images = [] for x in xrange (-scale_factor, front_image.size[0], scale_factor): left_image = Image.new('1', (front_image.size[0] * 2, front_image.size[1]), "white") left_image.paste(front_image, (x, 0)) right_image = Image.new('1', (front_image.size[0] * 2, front_image.size[1]), "white") right_image.paste(back_image, (front_image.size[0] - x, 0)) animated_image = ImageMath.eval("convert((a & b), 'L')", a=left_image, b=right_image) #animated_image.save(str(x) + ".png") animated_images.append(animated_image) return animated_images
def sketch(image, details_degree=1): im1 = image.convert('L') im2 = im1.copy() im2 = ImageOps.invert(im2) for i in xrange(details_degree): im2 = im2.filter(ImageFilter.BLUR) im1 = ImageMath.eval('convert(min(a * 255/ (256 - b), 255), "L")', a=im1, b=im2) return im1
def gen_captcha(text, fontname, fontsize, file_name): """Generate a captcha image""" # white text on a black background bgcolor = 0x0 fgcolor = 0xffffff # create a font object font = ImageFont.truetype(fontname,fontsize) # determine dimensions of the text dim = font.getsize(text) # create a new image significantly larger that the text edge = max(dim[0], dim[1]) + 2*min(dim[0], dim[1]) im = Image.new('RGB', (edge, edge), bgcolor) d = ImageDraw.Draw(im) x, y = im.size # add the text to the image d.text((x/2-dim[0]/2, y/2-dim[1]/2), text, font=font, fill=fgcolor) k = 2 wob = 0.09*dim[1] rot = 45 # Apply lots of small stirring operations, rather than a few large ones # in order to get some uniformity of treatment, whilst # maintaining randomness for i in range(k): im = wobbly_copy(im, wob, bgcolor, i*2+3, rot+0) im = wobbly_copy(im, wob, bgcolor, i*2+1, rot+45) im = wobbly_copy(im, wob, bgcolor, i*2+2, rot+90) rot += 30 # now get the bounding box of the nonzero parts of the image bbox = im.getbbox() bord = min(dim[0], dim[1])/4 # a bit of a border im = im.crop((bbox[0]-bord, bbox[1]-bord, bbox[2]+bord, bbox[3]+bord)) # Create noise nblock = 4 nsize = (im.size[0] / nblock, im.size[1] / nblock) noise = Image.new('L', nsize, bgcolor) data = noise.load() for x in range(nsize[0]): for y in range(nsize[1]): r = random.randint(0, 65) gradient = 70 * x / nsize[0] data[x, y] = r + gradient # Turn speckles into blobs noise = noise.resize(im.size, Image.BILINEAR) # Add to the image im = ImageMath.eval('convert(convert(a, "L") / 3 + b, "RGB")', a=im, b=noise) # and turn into black on white im = ImageOps.invert(im) # save the image, in format determined from filename im.save(file_name)
def test_logical(self): self.assertEqual(pixel(ImageMath.eval("not A", images)), 0) self.assertEqual(pixel(ImageMath.eval("A and B", images)), "L 2") self.assertEqual(pixel(ImageMath.eval("A or B", images)), "L 1")
def test_logical_ge(self): self.assertEqual(pixel(ImageMath.eval("A>=A", A=A)), "I 1") self.assertEqual(pixel(ImageMath.eval("B>=B", B=B)), "I 1") self.assertEqual(pixel(ImageMath.eval("A>=B", A=A, B=B)), "I 0") self.assertEqual(pixel(ImageMath.eval("B>=A", A=A, B=B)), "I 1")
def test_ops(self): self.assertEqual(pixel(ImageMath.eval("-A", images)), "I -1") self.assertEqual(pixel(ImageMath.eval("+B", images)), "L 2") self.assertEqual(pixel(ImageMath.eval("A+B", images)), "I 3") self.assertEqual(pixel(ImageMath.eval("A-B", images)), "I -1") self.assertEqual(pixel(ImageMath.eval("A*B", images)), "I 2") self.assertEqual(pixel(ImageMath.eval("A/B", images)), "I 0") self.assertEqual(pixel(ImageMath.eval("B**2", images)), "I 4") self.assertEqual(pixel(ImageMath.eval("B**33", images)), "I 2147483647") self.assertEqual(pixel(ImageMath.eval("float(A)+B", images)), "F 3.0") self.assertEqual(pixel(ImageMath.eval("float(A)-B", images)), "F -1.0") self.assertEqual(pixel(ImageMath.eval("float(A)*B", images)), "F 2.0") self.assertEqual(pixel(ImageMath.eval("float(A)/B", images)), "F 0.5") self.assertEqual(pixel(ImageMath.eval("float(B)**2", images)), "F 4.0") self.assertEqual(pixel(ImageMath.eval("float(B)**33", images)), "F 8589934592.0")
plt.ylabel('# of cells') plt.axes().yaxis.grid() plt.savefig(directory + '/neighbourhist' + info + '.png') # Overlay image if options.overlay: if len(overlay) == 1: image = Image.open(overlay[0]) else: image0 = Image.open(overlay[0]) image1 = Image.open(overlay[1]) r0, g0, b0 = image0.split()[0], image0.split()[1], image0.split()[2] r1, g1, b1 = image1.split()[0], image1.split()[1], image1.split()[2] r, g, b = ImageMath.eval('convert(max(a, b), "L")', a=r0, b=r1), \ ImageMath.eval('convert(max(a, b), "L")', a=g0, b=g1), \ ImageMath.eval('convert(max(a, b), "L")', a=b0, b=b1) image = Image.merge('RGB', (r, g, b)) image.save(directory + '/merged_image' + info + '.png') graph = Image.open(directory + '/cellgraph' + info + '.gv.png') ratio = float(image.size[0]) / image.size[1] image = image.resize((int(round(graph.size[1] * ratio)), graph.size[1])) bands = list(graph.split()) if len(bands) == 3: mask = Image.new('L', graph.size, color=128) graph.putalpha(mask) bands = list(graph.split())
def test_logical_lt(self): self.assertEqual(pixel(ImageMath.eval("A<A", A=A)), "I 0") self.assertEqual(pixel(ImageMath.eval("B<B", B=B)), "I 0") self.assertEqual(pixel(ImageMath.eval("A<B", A=A, B=B)), "I 1") self.assertEqual(pixel(ImageMath.eval("B<A", A=A, B=B)), "I 0")
def test_one_image_larger(self): self.assertEqual(pixel(ImageMath.eval("A+B", A=A2, B=B)), "I 3") self.assertEqual(pixel(ImageMath.eval("A+B", A=A, B=B2)), "I 3")
def test_compare(): assert_equal(pixel(ImageMath.eval("min(A, B)", images)), "I 1") assert_equal(pixel(ImageMath.eval("max(A, B)", images)), "I 2") assert_equal(pixel(ImageMath.eval("A == 1", images)), "I 1") assert_equal(pixel(ImageMath.eval("A == 2", images)), "I 0")
def watercolorize(mask, edge_texture, display_texture, texture_offsets, buffer_size, edge_multiplier=.2, edge_gauss=6, edge_threshold=90, outline_gauss=15, outline_multiplier=.7, aa_mult=2): ## print "using the right watercolorize:", buffer_size, edge_multiplier, edge_gauss, edge_threshold, outline_gauss, outline_multiplier, aa_mult ## edge_texture = edge_texture.point(lambda k:int(k * edge_multiplier)) ## tile the edger and texture as necessary to fit the mask edger_layer = Image.new("L", mask.size) for i in range(-1, (edger_layer.size[1] - buffer_size) / edge_texture.size[1] + 1): for j in range( -1, (edger_layer.size[0] - buffer_size) / edge_texture.size[1] + 1): edger_layer.paste( edge_texture, (edge_texture.size[0] * j - texture_offsets[0] - buffer_size, edge_texture.size[1] * i - texture_offsets[1] - buffer_size)) tex_layer = Image.new("RGBA", mask.size) for i in range( -1, (tex_layer.size[1] - buffer_size) / display_texture.size[1] + 1): for j in range( -1, (tex_layer.size[0] - buffer_size) / display_texture.size[1] + 1): tex_layer.paste(display_texture, (display_texture.size[0] * j - texture_offsets[0] - buffer_size, display_texture.size[1] * i - texture_offsets[1] - buffer_size)) artwork = mask.convert("L") dat = img2arr(artwork) edg = img2arr(edger_layer) gaussian(dat, edge_gauss) dat = add(dat * (1 - edge_multiplier), edg * edge_multiplier) dat = (dat > edge_threshold).astype(uint8) * 255 #blur, then unsharp mask to smooth pixelated edges gaussian(dat, 3) dat = usm(dat, 4, 15, 0) new_outline = arr2img(255 - dat) if outline_multiplier > 0: outlined = get_outlines_even(ImageOps.invert(new_outline), outline_gauss, outline_multiplier) old_bands = tex_layer.split() new_bands = [] for i in range(3): band1 = ImageOps.invert(old_bands[i]) band2 = outlined temp = ImageMath.eval("int(a/((float(b)+1)/256))", a=band1, b=band2).convert("L") new_bands.append(ImageOps.invert(temp)) outlined = Image.merge("RGB", new_bands) else: outlined = tex_layer alpha_test = outlined.convert("RGBA") alpha_test.putalpha(new_outline) return alpha_test
from PIL import Image, ImageFilter, ImageMath # Load an image from the hard drive original = Image.open("original.jpg") secret = Image.open("secret.jpg").resize(original.size) # Convert to black and white secret = secret.convert('1') # Split channels r, g, b = original.split() # Encode the secret in the last bit of the red channel out = ImageMath.eval("convert(a&254|b&1,'L')", a=r, b=secret) stegano = Image.merge("RGB", (out, g, b)) stegano.show() stegano.save("stegano.png")
#!/usr/bin/python from PIL import Image, ImageMath # beide Bilder laden Bild1 = Image.open("beuth-original.png") Bild2 = Image.open("beuth-verarbeitet.png") # Bild in einen Layer pro Farbkanal zerlegen (r1,g1,b1) = Bild1.split() (r2,g2,b2) = Bild2.split() # Bilder voneinander abziehen secret = ImageMath.eval("(b-a)*255", a=r1, b=r2).convert("P") secret.show()
def test_convert(): assert_equal(pixel(ImageMath.eval("convert(A+B, 'L')", images)), "L 3") assert_equal(pixel(ImageMath.eval("convert(A+B, '1')", images)), "1 0") assert_equal(pixel(ImageMath.eval("convert(A+B, 'RGB')", images)), "RGB (3, 3, 3)")
def test_bitwise_and(self): self.assertEqual(pixel(ImageMath.eval("Z&Z", A=A, Z=Z)), "I 0") self.assertEqual(pixel(ImageMath.eval("Z&A", A=A, Z=Z)), "I 0") self.assertEqual(pixel(ImageMath.eval("A&Z", A=A, Z=Z)), "I 0") self.assertEqual(pixel(ImageMath.eval("A&A", A=A, Z=Z)), "I 1")
def test_bitwise_invert(self): self.assertEqual(pixel(ImageMath.eval("~Z", Z=Z)), "I -1") self.assertEqual(pixel(ImageMath.eval("~A", A=A)), "I -2") self.assertEqual(pixel(ImageMath.eval("~B", B=B)), "I -3")
def test_abs(self): self.assertEqual(pixel(ImageMath.eval("abs(A)", A=A)), "I 1") self.assertEqual(pixel(ImageMath.eval("abs(B)", B=B)), "I 2")
def test_compare(self): self.assertEqual(pixel(ImageMath.eval("min(A, B)", images)), "I 1") self.assertEqual(pixel(ImageMath.eval("max(A, B)", images)), "I 2") self.assertEqual(pixel(ImageMath.eval("A == 1", images)), "I 1") self.assertEqual(pixel(ImageMath.eval("A == 2", images)), "I 0")
def diferenca_view(index): """Home.""" index = int(index) pontos = json.loads(DB.get("pontos_perspectiva")) b = Image.open(IMAGE_DIR + os.listdir(IMAGE_DIR)[index]).convert("L") b = perspectiva(b, pontos, (594, 420)) # b.show() a = Image.open(IMAGE_DIR + os.listdir(IMAGE_DIR)[index - 1]).convert("L") a = perspectiva(a, pontos, (594, 420)) # a.show() c = ImageMath.eval("a - b", a=a, b=b) e = Image.new("RGB", c.size, 0) f = e.load() d = c.load() for x in xrange(c.width): for y in xrange(c.height): cor = d[x, y] f[x, y] = (0, 0, 0) if cor < 0 else (cor, cor, cor) # e.show() arquivo = StringIO() e = ImageOps.invert(e) e = e.filter(ImageFilter.BLUR) enhancer = ImageEnhance.Brightness(e) e = enhancer.enhance(2) enhancer = ImageEnhance.Contrast(e) e = enhancer.enhance(8) e.save(arquivo, "png") e.save("/Users/nano/Desktop/teste.png") arquivo.seek(0) im = cv2.imread("/Users/nano/Desktop/teste.png") gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 150, apertureSize=3) lines = cv2.HoughLines(edges, 1, numpy.pi/180, 150) # lines = cv2.HoughLinesP(edges, 1, numpy.pi/180, 150) if lines is not None: for rho, theta in lines[0]: a = numpy.cos(theta) b = numpy.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) cv2.line(im, (x1, y1), (x2, y2), (0, 0, 255), 2) # if lines is not None: # for x1, y1, x2, y2 in lines[0]: # cv2.line(im, (x1, y1), (x2, y2), (0, 0, 255), 2) # frame_string = im.tostring() # e = Image.frombytes('RGB', (im.shape[1], im.shape[0]), frame_string) # # Create a detector with the parameters params = cv2.SimpleBlobDetector_Params() # # Change thresholds # params.minThreshold = 10 # params.maxThreshold = 200 # # Filter by Area. params.filterByArea = True params.maxArea = 400 # # Filter by Circularity params.filterByCircularity = True params.minCircularity = 0.1 # # Filter by Convexity params.filterByConvexity = True params.minConvexity = 0.1 # # Filter by Inertia params.filterByInertia = True params.minInertiaRatio = 0.01 # # Set up the detector with default parameters. # detector = cv2.SimpleBlobDetector() detector = cv2.SimpleBlobDetector(params) # # Detect blobs. keypoints = detector.detect(im) # print keypoints # # Draw detected blobs as red circles. # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob im = cv2.drawKeypoints(im, keypoints, numpy.array([]), (0,255,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # frame_string = im_with_keypoints.tostring() # e = Image.frombytes('RGB', (im_with_keypoints.shape[1], im_with_keypoints.shape[0]), frame_string) ret, thresh = cv2.threshold(gray, 127, 255, 0) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # cv2.drawContours(im, contours, -1, (0,255,0), 3) cores = [(255, 0, 0), # vermelho (0, 255, 0), # verde (0, 0, 255), (127, 0, 0), (0, 127, 0), (0, 0, 127), (255, 255, 0), (0, 255, 255), (255, 0, 255)] for i in range(len(contours))[1:]: cnt = contours[i] cv2.drawContours(im, [cnt], 0, (255, 255, 255), cv2.cv.CV_FILLED) frame_string = im.tostring() e = Image.frombytes('RGB', (im.shape[1], im.shape[0]), frame_string) arquivo = StringIO() e.save(arquivo, "png") arquivo.seek(0) response = send_file(arquivo, as_attachment=False, attachment_filename="diferenca.png") return response
def im_not(im1): return ImageMath.eval("~B", B=im1)
def __init__(self, testImage, refImage, allowDifferentImageMode=False, enhance=10): self.testImage = Image.open(testImage) self.refImage = Image.open(refImage) self.maskImage = None self.diffImage = None self.difference = 100 self.numberOfDifferentPixels = None self.maxDifference = None if self.testImage.size != self.refImage.size: return if self.testImage.mode != self.refImage.mode: if not allowDifferentImageMode: return self.refImage = self.refImage.convert(self.testImage.mode) # ImageChops.difference does not work for signed integers if self.testImage.mode == 'I': self.testImage = self.testImage.convert('L') self.refImage = self.refImage.convert('L') numPixels = self.testImage.size[0] * self.testImage.size[1] self.diffImage = ImageChops.difference(self.testImage, self.refImage) channels = len(self.testImage.getbands()) if channels == 1: normImage = self.diffImage elif channels == 2: (a, b) = self.diffImage.split() normImage = ImageMath.eval("convert((a+b), 'L')", a=a, b=b) elif channels == 3: (a, b, c) = self.diffImage.split() normImage = ImageMath.eval("convert((a+b+c), 'L')", a=a, b=b, c=c) elif channels == 4: (a, b, c, d) = self.diffImage.split() normImage = ImageMath.eval("convert((a+b+c+d), 'L')", a=a, b=b, c=c, d=d) self.maskImage = normImage.point(lambda p: 0 if p > 0 else 255, 'L') stats = ImageStat.Stat(normImage) self.maxDifference = stats.extrema[0][1] / (channels * 255) self.difference = (sum(stats.sum) / (255 * channels)) * 100.0 / numPixels if enhance != 1: self.diffImage = self.diffImage.point(lambda i: i * (enhance)) self.diffImage = ImageChops.invert(self.diffImage) self.numberOfDifferentPixels = int( numPixels - ImageStat.Stat(self.maskImage).sum[0] / 255)
draw.rectangle((0, 0, width / 2, height / 2), fill=0) draw.rectangle((width / 2, 0, width, height / 2), fill=127) draw.rectangle((0, height / 2, width / 2, height), fill=128) draw.rectangle((width / 2, height / 2, width, height), fill=255) del draw return second_image try: # načtení originálního obrázku Leny original_image = Image.open(filename) original_image.load() # převod na úrovně šedi grayscale_image = ImageMath.eval("convert(src, 'L')", src=original_image) # vytvoření druhého obrázku s maskou second_image = create_second_image(512, 512) # aplikace operace result_image = ImageMath.eval("first & second", first=grayscale_image, second=second_image) # další převod výsledku na stupně šedi result_image = ImageMath.eval("convert(src, 'L')", src=result_image) # zobrazení výsledného obrázku uživateli result_image.show()
def chromeKeyBluescreen(r, g, b): # return an alpha image with mode 'F' # the r,g,b and white should be 'F' mode # we use 'F' mode in case of negative value global white return ImageMath.eval('r+g-b+d', r=r, g=g, b=b, d=white)
def im_and(im1, im2): return ImageMath.eval("A & B", A=im1, B=im2)
def test_bitwise_or(self): self.assertEqual(pixel(ImageMath.eval("Z|Z", A=A, Z=Z)), "I 0") self.assertEqual(pixel(ImageMath.eval("Z|A", A=A, Z=Z)), "I 1") self.assertEqual(pixel(ImageMath.eval("A|Z", A=A, Z=Z)), "I 1") self.assertEqual(pixel(ImageMath.eval("A|A", A=A, Z=Z)), "I 1")
def im_xor(im1, im2): return ImageMath.eval("A ^ B", A=im1, B=im2)
def test_bitwise_xor(self): self.assertEqual(pixel(ImageMath.eval("Z^Z", A=A, Z=Z)), "I 0") self.assertEqual(pixel(ImageMath.eval("Z^A", A=A, Z=Z)), "I 1") self.assertEqual(pixel(ImageMath.eval("A^Z", A=A, Z=Z)), "I 1") self.assertEqual(pixel(ImageMath.eval("A^A", A=A, Z=Z)), "I 0")
def test_bitwise_leftshift(self): self.assertEqual(pixel(ImageMath.eval("Z<<0", Z=Z)), "I 0") self.assertEqual(pixel(ImageMath.eval("Z<<1", Z=Z)), "I 0") self.assertEqual(pixel(ImageMath.eval("A<<0", A=A)), "I 1") self.assertEqual(pixel(ImageMath.eval("A<<1", A=A)), "I 2")
def test_bitwise_rightshift(self): self.assertEqual(pixel(ImageMath.eval("Z>>0", Z=Z)), "I 0") self.assertEqual(pixel(ImageMath.eval("Z>>1", Z=Z)), "I 0") self.assertEqual(pixel(ImageMath.eval("A>>0", A=A)), "I 1") self.assertEqual(pixel(ImageMath.eval("A>>1", A=A)), "I 0")
def _color_to_alpha(image: Image, color=None) -> Image: """ Implements GIMP's color to alpha algorithm. See https://stackoverflow.com/a/1617909 GPLv3: http://bazaar.launchpad.net/~stani/phatch/trunk/annotate/head:/phatch/actions/color_to_alpha.py#L50 INPUTS image: A PIL image to work on color: A 4-tuple (R, G, B, A) value as the color to change to alpha OUTPUTS A string of XML representing the new SVG """ image = image.convert("RGBA") color = list(map(float, color)) img_bands = [band.convert("F") for band in image.split()] # Find the maximum difference rate between source and color. I had to use two # difference functions because ImageMath.eval only evaluates the expression # once. alpha = ImageMath.eval("""float( max( max( max( difference1(red_band, cred_band), difference1(green_band, cgreen_band) ), difference1(blue_band, cblue_band) ), max( max( difference2(red_band, cred_band), difference2(green_band, cgreen_band) ), difference2(blue_band, cblue_band) ) ) )""", difference1=lambda source, color: (source - color) / (255.0 - color), difference2=lambda source, color: (color - source) / color, red_band=img_bands[0], green_band=img_bands[1], blue_band=img_bands[2], cred_band=color[0], cgreen_band=color[1], cblue_band=color[2]) # Calculate the new image colors after the removal of the selected color new_bands = [ ImageMath.eval("convert((image - color) / alpha + color, 'L')", image=img_bands[i], color=color[i], alpha=alpha) for i in range(3) ] # Add the new alpha band new_bands.append( ImageMath.eval("convert(alpha_band * alpha, 'L')", alpha=alpha, alpha_band=img_bands[3])) new_image = Image.merge("RGBA", new_bands) background = Image.new("RGB", new_image.size, (0, 0, 0, 0)) background.paste(new_image.convert("RGB"), mask=new_image) # SE addition: Lastly, convert transparent pixels to rgba(0, 0, 0, 0) so that Pillow's # crop function can detect them. # See https://stackoverflow.com/a/14211878 pixdata = new_image.load() width, height = new_image.size for image_y in range(height): for image_x in range(width): if pixdata[image_x, image_y] == (255, 255, 255, 0): pixdata[image_x, image_y] = (0, 0, 0, 0) return new_image
def get_mask(image): r, g, b, _ = image.split() r_mask = r.point(lambda i: i > 0 and 255) g_mask = g.point(lambda i: i > 0 and 255) b_mask = b.point(lambda i: i > 0 and 255) return ImageMath.eval("convert(a | b | c, 'L')", a=r_mask, b=g_mask, c=b_mask)
#!/usr/bin/env python3 # vim: set fileencoding=utf-8 from PIL import Image from PIL import ImageMath filename = "Lenna.png" try: test_image = Image.open(filename) test_image.load() modified_image = ImageMath.eval("convert(src, 'L')", src=test_image) modified_image.save("Lenna_grayscale.png") except Exception as e: print(e)
def test_logical(): assert_equal(pixel(ImageMath.eval("not A", images)), 0) assert_equal(pixel(ImageMath.eval("A and B", images)), "L 2") assert_equal(pixel(ImageMath.eval("A or B", images)), "L 1")