def process(self, image): yield 'Start...', image simage = ImageOps.autocontrast(image, 20) s_width, s_height = image.size[0] / 2, image.size[1] / 2 simage = image.resize((s_width, s_height)) simage = simage.filter(ImageFilter.SMOOTH) yield 'Mask...', simage mask = ImageEnhance.Brightness(simage).enhance(2) mask = ImageOps.posterize(mask, 2) mask = ImageOps.autocontrast(mask, 20) yield 'posterize...', mask simage = ImageEnhance.Brightness(simage).enhance(2) simage = ImageOps.equalize(simage) simage = simage.filter(ImageFilter.SMOOTH_MORE) simage = ImageOps.posterize(simage, 1) yield 'Red...', simage red_img = self._apply_color(simage, 0.25, mask) yield 'green...', red_img green_img = self._apply_color(simage, 0.75, mask) yield 'blue...', green_img blue_img = self._apply_color(simage, 1, mask) yield 'yellow...', blue_img yellow_img = self._apply_color(simage, 0.5, mask) yield 'Merge...', yellow_img image = image.copy() image.paste(red_img, (0, 0, s_width, s_height)) image.paste(green_img, (s_width, 0, s_width * 2, s_height)) image.paste(yellow_img, (0, s_height, s_width, s_height * 2)) image.paste(blue_img, (s_width, s_height, s_width * 2, s_height * 2)) yield 'Done', image
def render(meshes, fileName, wireFrame=False): global initialized, SIZE assert initialized glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) for mesh in meshes: glPolygonMode(GL_FRONT_AND_BACK, (GL_LINE if wireFrame else GL_FILL)) glPushMatrix() # apply transformations glColor3f(*mesh.getColor()) glTranslatef(*mesh.getTranslation()) glScalef(*mesh.getScale()) glRotatef(mesh.getRotation()[2], 0, 0, 1) glRotatef(mesh.getRotation()[1], 0, 1, 0) glRotatef(mesh.getRotation()[0], 1, 0, 0) # send triangles glBegin(GL_TRIANGLES) for triangle in mesh.getTriangles(): for vertex in triangle: glVertex3f(vertex[0], vertex[1], vertex[2]) glEnd() glPopMatrix() glFlush() glutSwapBuffers() # save the framebuffer to disk data = glReadPixels(0, 0, SIZE[0], SIZE[1], GL_RGB, GL_BYTE) img = Image.frombuffer('RGB', SIZE, data, 'raw', 'RGB') flipped = ImageOps.mirror(ImageOps.flip(img)) flipped.save(fileName)
def green_key(canvas,key_image,img_source,mtype=KEY_REG): s3 = key_image.split() mask = (s3[1].point(lambda i: (i > 254 or 256))) # cut out green area (overlay) if(mtype == KEY_BLUR or mtype == KEY_BLUR_BRIGHT or mtype == KEY_BLUR_BRIGHT_MORE): mask = mask.filter(ImageFilter.SMOOTH_MORE) mask = mask.filter(ImageFilter.BLUR) mask = mask.filter(ImageFilter.SMOOTH_MORE) if(mtype == KEY_BLUR_BRIGHT): mask = (mask.point(lambda k: (k*2))) elif(mtype == KEY_BLUR_BRIGHT_MORE): mask = (mask.point(lambda k: k > 20 and (k*k))) # mask.show() # mask.save("images/saved/mask.jpg") # canvas.convert("RGBA") # needed? if(canvas.size != img_source.size): # fix image size if(canvas.size < img_source.size): print "resizing canvas", canvas.size, img_source.size, key_image.size canvas = ImageOps.fit(canvas,img_source.size) else: print "resizing img_source and mask", canvas.size, img_source.size, key_image.size img_source = ImageOps.fit(img_source,canvas.size) mask = ImageOps.fit(mask,canvas.size) image = Image.composite(img_source,canvas,mask) return image
def process(self, image): yield 'Start...', image simage = ImageOps.autocontrast(image, 20) s_width, s_height = image.size[0] / 2, image.size[1] / 2 simage = image.resize((s_width, s_height)) simage = colors.convert_to_luminosity(simage) simage = simage.filter(ImageFilter.SMOOTH) yield 'Mask...', simage mask = ImageEnhance.Brightness(simage).enhance(2) mask = ImageOps.posterize(mask, 2) mask = ImageOps.autocontrast(mask, 20) yield 'Curves...', mask simage = ImageEnhance.Contrast(simage).enhance(2) yield 'posterize...', simage simage = ImageOps.posterize(simage, 2) yield 'Red...', simage red_img = self._apply_color(simage, (255, 0, 0), mask) yield 'green...', red_img green_img = self._apply_color(simage, (0, 255, 0), mask) yield 'blue...', green_img blue_img = self._apply_color(simage, (0, 0, 255), mask) yield 'yellow...', blue_img yellow_img = self._apply_color(simage, (255, 255, 0), mask) yield 'Merge...', yellow_img image = image.copy() image.paste(red_img, (0, 0, s_width, s_height)) image.paste(green_img, (s_width, 0, s_width * 2, s_height)) image.paste(yellow_img, (0, s_height, s_width, s_height * 2)) image.paste(blue_img, (s_width, s_height, s_width * 2, s_height * 2)) yield 'Done', image
def main(argv): parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--mirror-x', action='store_true') parser.add_argument('--mirror-y', action='store_true') parser.add_argument('--no-display', action='store_false', dest='display') parser.add_argument('--no-click', action='store_false', dest='clicks') args = parser.parse_args(argv[1:]) am = AutoMeta() print "Getting images..." pos, im1, im2 = get_images(am) if args.mirror_x: im2 = ImageOps.mirror(im2) if args.mirror_y: im2 = ImageOps.flip(im2) print "got" print "Aligning..." pix = get_difference_image(im1, im2) print "done" print "Finding differences...", diffs = get_difference_spots(pix) print "done" if args.clicks: # TODO: if two diffs are very close, only click one for diff in diffs: am.move_mouse(pos[0] + diff[1], pos[1] + diff[0]) time.sleep(.1) am.left_click() if args.display: Image.fromarray(pix).show()
def symbols_in(image): symbols = [] cut = [] pixels = 0 for i in range(image.size[0]): whitespace = True for j in range(image.size[1]): if image.getpixel((i, j)) != (255, 255, 255): whitespace = False break if whitespace: if pixels > 0: cut = cut + [i] pixels = 0 else: pixels = pixels + 1 if pixels > 0: cut = cut + [i] pixels = 0 x = 0 for i in range(len(cut)): image = ImageOps.invert(image) crop = image.crop([x, 0, cut[i], image.size[1]]) image = ImageOps.invert(image) x = cut[i] symbols = symbols + [ImageOps.invert(crop)] return symbols
def geticonshape(shape, dim_horiz, dim_vert): iconimage = ''.join([shape, '_icon.png']) img = Image.open(iconimage) img = ImageOps.grayscale(img) img = ImageOps.autocontrast(img) img = img.resize((dim_horiz, dim_vert), Image.BILINEAR) return img
def put_contour(image, size=1, offset=0, contour_color=0, fill_color=0, opacity=100, include_image=True): if not has_transparency(image): return put_border( image, size, offset, contour_color, fill_color, opacity, include_image) image = image.convert('RGBA') mask = imtools.get_alpha(image) w, h = image.size outer_mask = mask.resize( (w + 2 * (size + offset), h + 2 * (size + offset)), Image.ANTIALIAS) inner_mask = mask.resize( (w + 2 * offset, h + 2 * offset), Image.ANTIALIAS) inner_mask = ImageOps.expand(inner_mask, border=size, fill=0) paste(outer_mask, (255 * opacity) / 100, mask=inner_mask) if include_image: image = ImageOps.expand(image, border=size + offset, fill=(0, 0, 0, 0)) mask = ImageOps.expand(mask, border=size + offset, fill=0) paste(outer_mask, 255, mask=mask) contour = ImageOps.colorize(outer_mask, (255, 255, 255), contour_color) paste(contour, fill_color, mask=inner_mask) if include_image: paste(contour, image, mask=image) contour.putalpha(outer_mask) return contour
def resize(relative_path, size, method): image_file = os.path.join(settings.MEDIA_ROOT, relative_path) relative_resized_path = resized_path(relative_path, size, method) resized_file = os.path.join(settings.MEDIA_ROOT, relative_resized_path) relative_url = os.path.join(settings.MEDIA_URL, relative_resized_path) # Parse size string 'WIDTHxHEIGHT' width, height = [int(i) for i in size.split('x')] if os.path.exists(resized_file): return relative_url try: image = Image.open(image_file) except: return settings.STATIC_URL + 'g/blank.png' if image.mode != 'RGB': image = image.convert('RGB') # use PIL methods to edit images if method == 'scale': image.thumbnail((width, height), Image.ANTIALIAS) image.save(resized_file, FORMAT, quality=QUALITY) elif method == 'crop': ImageOps.fit(image, (width, height), Image.ANTIALIAS).save( resized_file, FORMAT, quality=QUALITY) return relative_url
def draw_mask(angle,width,height,offset_init,offset_A,offset_focus,offset_B): offset = height*offset_init/100 vectorA = offset+offset_A*height/100 focus = vectorA+offset_focus*height/100 vectorB = focus+offset_B*height/100 mask = Image.new('L', (width,height)) mask_1px = Image.new('L', (1,height)) draw_1px = ImageDraw.Draw(mask_1px) for y in range (0,offset): # draw white zone draw_1px.point((0,y),255) for y in range (offset,vectorA): # draw vectorA draw_1px.point((0,y),(vectorA-y)*(255/(vectorA-offset))) for y in range (vectorA,focus): # draw white zone draw_1px.point((0,y),0) for y in range (focus,vectorB): # draw vectorB draw_1px.point((0,y),255-(vectorB-y)*(255/(vectorB-focus))) for y in range (vectorB,height): # draw white zone draw_1px.point((0,y),255) m_width,m_height = mask.size mask_1px = mask_1px.resize((int(m_width*3),m_height), Image.ANTIALIAS) mask_1px = ImageOps.invert(mask_1px) mask_top = mask_1px.rotate(angle,Image.NEAREST,1) mask_top = ImageOps.invert(mask_top) mask.convert("RGBA") n_width,n_height = mask_top.size mask.paste(mask_top,(-n_width/2,-(n_height/2-height/2))) mask.convert("L") return mask
def create_photo_strips(): '''using the original images we build a color and black and white photo strip and save it to photos/strips''' strip = Image.new('RGB', (PHOTO_HEIGHT + (BORDER_WIDTH * 2) + FOOTER_HEIGHT, (PHOTO_WIDTH * PHOTO_COUNT) + (BORDER_WIDTH * 2)), BG_COLOR) for i in range(PHOTO_COUNT): photo = Image.open(PHOTO_FOLDER + str(i+1) + '.' + PHOTO_FILE_EXTENSION) w, h = map(lambda x: x/2, photo.size) photo = ImageOps.fit(photo, (PHOTO_WIDTH, PHOTO_HEIGHT), centering=(0.5, 0.5)) photo = photo.rotate(270) photo = ImageOps.autocontrast(photo, cutoff=0) strip.paste(photo, (FOOTER_HEIGHT, (i * PHOTO_WIDTH) + (i * BORDER_WIDTH))) #append footer font = ImageFont.truetype('font_1.ttf', 40) footer_img = Image.new("RGB", ((PHOTO_COUNT * PHOTO_WIDTH) + (PHOTO_COUNT * BORDER_WIDTH), FOOTER_HEIGHT), BG_COLOR) draw = ImageDraw.Draw(footer_img) draw.text((220, 40), "ashley & david's wedding, july 28, 2012", font=font, fill=(100,100,0)) strip.paste(footer_img.rotate(270), (0,0)) strip.save(COLOR_FOLDER + current_timestamp() + '.png', PHOTO_FORMAT) ImageOps.grayscale(strip).save(GREYSCALE_FOLDER + current_timestamp() + '.png', PHOTO_FORMAT) strip_to_print = Image.new('RGB', (PAGE_WIDTH, PAGE_HEIGHT), BG_COLOR) strip_to_print.paste(ImageOps.grayscale(strip), (-BORDER_WIDTH, -BORDER_WIDTH)) strip_to_print.save('to_print.png', PHOTO_FORMAT) return 'to_print.png'
def tats(image): image = image.convert('RGB') colours = util.get_dominant_colours(image, 9) colours = util.order_colours_by_brightness(colours) bg = random.choice(colours[:3]) light = random.choice(colours[3:6]) dark = random.choice(colours[6:]) dist = math.sqrt(sum(map(lambda (a, b): math.pow(a - b, 2), zip(light, dark)))) if dist < 100: light = util.modify_hls(light, l=lambda l: l + 100) light = util.modify_hls(light, s=lambda s: s + 100) dark = util.modify_hls(dark, s=lambda s: s + 100) layer = Image.open(os.path.dirname(os.path.abspath(__file__)) + '/' + 'assets/tats.png') layer.load() r, g, b, a = layer.split() layer = layer.convert('RGB') layer = ImageOps.grayscale(layer) layer = ImageOps.colorize(layer, tuple(dark), tuple(light)) layer.putalpha(a) im = Image.new('RGB', layer.size, tuple(bg)) im.paste(layer, mask=layer) return im
def process(self, image): yield 'Start...', image s_width, s_height = image.size[0] / 3, image.size[1] / 3 simage = image.resize((s_width, s_height)) yield 'posterize...', simage simage = simage.convert("L") simage = ImageEnhance.Brightness(simage).enhance(2) simage = ImageOps.equalize(simage) simage = ImageOps.autocontrast(simage, 20) simage = ImageOps.posterize(simage, 1) yield 'colors...', simage colormap = [] colormap.extend([255] * 128) colormap.extend([0] * 128) colormap.extend([0] * 128) colormap.extend([255] * 128) colormap.extend([0] * 256) simage = simage.convert("RGB").point(colormap) image = image.copy() for x in xrange(3): for y in xrange(3): yield 'Img %d...' % (x * 3 + y + 1), simage simg = colors.apply_hue_lightness_saturation(simage, ((x * 3 + (2.9 - y)) / 10.), 0, 1, True) image.paste(simg, (x * s_width, y * s_height, (x + 1) * s_width, (y + 1) * s_height)) yield 'Done', image
def generate_thumbnail(path, size, method): try: import Image except ImportError: try: from PIL import Image except ImportError: raise ImportError('Cannot import the Python Image Library.') image = Image.open(path) # normalize image mode if image.mode != 'RGB': image = image.convert('RGB') # parse size string 'WIDTHxHEIGHT' width, height = [int(i) for i in size.split('x')] # use PIL methods to edit images if method == 'scale': image.thumbnail((width, height), Image.ANTIALIAS) image.save(thumbnail_path(path, size, method), MEDIA_IMAGE_FORMAT, quality=MEDIA_IMAGE_QUALITY) elif method == 'crop': try: import ImageOps except ImportError: from PIL import ImageOps ImageOps.fit( image, (width, height), Image.ANTIALIAS ).save(thumbnail_path(path, size, method), MEDIA_IMAGE_FORMAT, quality=MEDIA_IMAGE_QUALITY)
def update(self, control): Effect.update(self, control) img = Image.new("RGB", self.providers[0].size) src_img = self.providers[0].getImage(self.currentFrame) size = self.providers[0].size x = 0 for i in range(self.sliceCount): w = int(size[0] * (float(self.percentages[i]) / float(100))) l = x x += w r = x if i > self.__current_slice: tmpimg = ImageOps.fit(src_img, (w,img.size[1])) img.paste(tmpimg, (l,0,r,tmpimg.size[1])) if i == self.__current_slice + 1: self.__end_x = l if self.__current_slice >= 0: start_x = int(self.__x) # paste left half tmpimg = ImageOps.fit(src_img, (start_x, img.size[1])) img.paste(tmpimg, (0,0,start_x, tmpimg.size[1])) # paste right half tmpimg = ImageOps.fit(src_img, ((self.__end_x - start_x), img.size[1])) img.paste(tmpimg, (start_x, 0, self.__end_x, tmpimg.size[1])) #self.__x += int(self.step_size[self.__current_slice]) self.__x += self.__step_size if self.__x >= self.pixels[self.__current_slice]: self.__x = 0.00 self.__current_slice -= 1 self.keeper.setImage(img)
def load_image(self, idx): filename = self.X[idx] import Image import ImageOps # print "loading ", self.X[idx] image = Image.open(self.X[idx]) width, height = image.size if width > height: delta2 = int((width - height)/2) image = ImageOps.expand(image, border=(0, delta2, 0, delta2)) else: delta2 = int((height - width)/2) image = ImageOps.expand(image, border=(delta2, 0, delta2, 0)) image = image.resize((self.width, self.width), resample=Image.BICUBIC) try: imagenp = np.array(image.getdata()).reshape((self.width,self.width,3)) imagenp = imagenp.transpose((2,0,1)) # move color channels to beginning except: # print "reshape failure (black and white?)" imagenp = self.load_image(np.random.randint(len(self.X))) return imagenp.astype(theano.config.floatX)
def addUniqueData(self, filename, inputType, normalized=False): import os if not os.path.isfile(filename): raise Exception("addUniqueData : \"" + filename + "\" is not a file") if inputType >= DataCategory.TRAIN and inputType <= DataCategory.TEST: im = Normalize(self.Size(), filename, offset=self.__offset) array = [] import ImageOps if self.__grayScale: im = ImageOps.grayscale(im) if self.__negate: im = ImageOps.invert(im) if normalized: array = [float(x) / 255. for x in list(im.getdata())] else: array = [x for x in list(im.getdata())] else: for p in list(im.getdata()): # array.append(zip([float(x)/255. for x in p])) for i in xrange(len(p)): if normalized: array.append(float(p[i]) / 255.) else: array.append(p[i]) array = [x for x in array] self.Inputs()[inputType].append(array) import string groundTruth = string.split(os.path.splitext(os.path.split(filename)[1])[0], '-')[0] self.Targets()[inputType].append(int(groundTruth)) else: raise Exception("Incorrect DataCategory")
def resizeImage(self, file_path, th_width = 200, th_height = 200, or_width = 1000, or_height = 800): image = Image.open(file_path) # Crop and make thumbnails thumb = ImageOps.fit(image, (th_width, th_height), Image.ANTIALIAS) thumb64 = ImageOps.fit(image, (64, 64), Image.ANTIALIAS) # Resize original image.thumbnail((or_width, or_height), Image.ANTIALIAS) old_filename = file_path.rsplit('/', 1)[1] thumb_filename = old_filename.rsplit('.', 1)[0] + "_thumb.jpg" thumb_filename = thumb_filename.replace(" ", "_") new_filename = thumb_filename.replace(" ", "_") thumb.save(self.THUMB_DIR + thumb_filename, "JPEG", quality=100) thumb64.save(self.THUMB64_DIR + thumb_filename, "JPEG", quality=100) image.save(self.NEW_ORIGINAL_DIR + new_filename, "JPEG", quality=100) return { 'original': old_filename, 'new_original': new_filename, 'thumbnail': thumb_filename }
def process(self, image): yield 'Start...', image s_width, s_height = image.size[0] / 2, image.size[1] / 2 simage = image.resize((s_width, s_height)) yield 'posterize...', simage simage = simage.convert("L") yield 'posterize 2...', simage simage = ImageEnhance.Brightness(simage).enhance(2) simage = ImageOps.equalize(simage) yield 'posterize 3...', simage simage = ImageOps.autocontrast(simage, 20) yield 'posterize 4...', simage simage = ImageOps.posterize(simage, 1) colors = [] colors.extend([255] * 128) colors.extend([0] * 128) colors.extend([0] * 128) colors.extend([255] * 128) colors.extend([0] * 256) simage = simage.convert("RGB").point(colors) yield 'Red...', simage red_img = self._apply_color(simage, 0.82) yield 'green...', red_img green_img = self._apply_color(simage, 0.75) yield 'blue...', green_img blue_img = self._apply_color(simage, 0) yield 'yellow...', blue_img yellow_img = self._apply_color(simage, 0.6) yield 'Merge...', yellow_img image = image.copy() image.paste(red_img, (0, 0, s_width, s_height)) image.paste(green_img, (s_width, 0, s_width * 2, s_height)) image.paste(yellow_img, (0, s_height, s_width, s_height * 2)) image.paste(blue_img, (s_width, s_height, s_width * 2, s_height * 2)) yield 'Done', image
def triangles(original, n=30, size=150, width=700, height=700, min_distance=70, opacity=220): original = original.convert('RGB') colours = util.get_dominant_colours(original, 8) colours_ordered = util.order_colours_by_brightness(colours) brightest_colour = list(random.choice(colours_ordered[:3])) brightest_colour.append(0) new = Image.new('RGBA', (width, height), tuple(brightest_colour)) draw = aggdraw.Draw(new) centres = [] def is_too_close(x, y): for centre in centres: if math.sqrt(math.pow(centre[0] - x, 2) + math.pow(centre[1] - y, 2)) < min_distance: return True return False for i in xrange(n): colour = tuple(colours[int(random.randint(0, len(colours) - 1))]) x = random.randint(size / 2, width - 1 - size / 2) y = random.randint(size / 2, height - 1 - size / 2) if is_too_close(x, y): continue centres.append((x, y)) brush = aggdraw.Brush(colour, opacity) points = get_triangle_path(x, y, size / 2, size / 2) draw.polygon(points, None, brush) draw.flush() brightest_colour = brightest_colour[0:3] texture = Image.open(os.path.dirname(os.path.abspath(__file__)) + '/' + 'assets/airbrush.png') texture = texture.convert('RGBA') r, g, b, a = texture.split() texture = ImageOps.grayscale(texture) texture = ImageOps.colorize(texture, (0, 0, 0), tuple(brightest_colour)) texture = texture.convert('RGBA') texture.putalpha(a) r, g, b, a = new.split() texture = texture.crop((0, 0, width, height)) texture_layer = Image.new('RGBA', (width, height), (0, 0, 0, 0)) texture_layer.paste(texture, mask=new) new.paste(texture_layer, mask=texture_layer) im = Image.new('RGB', (width, height), tuple(brightest_colour)) im.paste(new, mask=a) return im
def make_image_square(image, img_sz, outfile=None, overwrite=False): """ Will resize an image. Parameters ---------- image : Image.Image or str The image to transform. If str it is interpreted to be a path. img_sz : int New size for that image. Returns ------- image : Image.image The transformed image. """ if isinstance(image, basestring): image = Image.open(image) #NEAREST, BILINEAR, BICUBIC, ANTIALIAS #image = image.resize((img_sz, img_sz), resample=Image.BICUBIC) width, height = image.size if width > height: delta2 = int((width - height)/2) image = ImageOps.expand(image, border=(0, delta2, 0, delta2)) else: delta2 = int((height - width)/2) image = ImageOps.expand(image, border=(delta2, 0, delta2, 0)) image = image.resize((img_sz, img_sz), resample=Image.BICUBIC) if not outfile is None: if image.mode == 'P': fbase, ext = os.path.splitext(outfile) if ext == '.jpg' or ext == '.jpeg': orig_out = outfile outfile = '%s.png' % fbase logging.info('%s renamed to %s because jpg ' 'does not support palletes', orig_out, outfile) if os.path.isfile(outfile): if not overwrite: logging.info('%s exists; skipping', outfile) return image orig_out = outfile for ext in ('%s.png', '%s.jpg', '%s.bmp', '%s.tiff', '%s'): try: image.save(outfile) break except (KeyError, IOError): fbase, old_ext = os.path.splitext(outfile) outfile = ext % fbase if ext == '%s': logging.error('unable to save %s', orig_out) return image
def scale(imagefield, method='scale'): """ Template filter used to scale an image that will fit inside the defined area. Returns the url of the resized image. {% load image_tags %} {{ profile.picture|scale }} """ if not imagefield: return None # imagefield can be a dict with "path" and "url" keys if imagefield.__class__.__name__ == 'dict': imagefield = type('imageobj', (object,), imagefield) image_path = resized_path(imagefield.path, method) #thumb_path = os.path.join(settings.MEDIA_ROOT, "%s_%s_%s.%s" % (imagefield.name.rsplit('.', 1)[0], method, EXT)) #thumb_url = "%s_%s_%s.%s" % (imagefield.url.rsplit('.', 1)[0], method, EXT) #print thumb_path, thumb_url if not os.path.exists(image_path): try: import Image except ImportError: try: from PIL import Image except ImportError: raise ImportError('Cannot import the Python Image Library.') image = Image.open(imagefield.path) # normalize image mode if image.mode != 'RGB': image = image.convert('RGB') # use PIL methods to edit images if method == 'scale': width, height = [int(i) for i in IMAGE_SIZE.split('x')] image.thumbnail((width, height), Image.ANTIALIAS) image.save(image_path, FMT, quality=QUAL) elif method == 'crop': try: import ImageOps except ImportError: from PIL import ImageOps width, height = [int(i) for i in THUMBNAIL_SIZE.split('x')] ImageOps.fit(image, (width, height), Image.ANTIALIAS ).save(image_path, FMT, quality=QUAL) return resized_path(imagefield.url, method)
def process(self, _edObject=None): """ This is the main method of the plugin, it does the job, not the EDNA name conversions which were done in the preprocess. """ EDPluginExec.process(self) EDVerbose.DEBUG("EDPluginPyarchThumbnailv10.process") if self.inputFilename: # Read the image using FABIO fabioImage = openimage(self.inputFilename) # Convert an FabioImage to a PIL image npaImageRaw = fabioImage.data iMinLevel = 2 iMaxLevel = 1000 npaImageRaw = numpy.minimum(npaImageRaw, iMaxLevel * numpy.ones_like(npaImageRaw)) npaImageRaw = numpy.maximum(npaImageRaw, iMinLevel * numpy.ones_like(npaImageRaw)) npaImage = scipy.ndimage.morphology.grey_dilation(npaImageRaw, size=(5, 5)) npaImageThumb = scipy.ndimage.morphology.grey_dilation(npaImageRaw, size=(10, 10)) dtype = str(npaImage.dtype) if dtype == "uint8": NPAImageFloat = npaImage.astype("float") / 255.0 NPAImageFloatThumb = npaImageThumb.astype("float") / 255.0 elif dtype == "uint16": NPAImageFloat = npaImage.astype("float") / 65535.0 NPAImageFloatThumb = npaImageThumb.astype("float") / 65535.0 else: #for float or whatever vmin = npaImage.min() vmax = npaImage.max() NPAImageFloat = (npaImage.astype(float) - vmin) / (vmax - vmin) vminThumb = npaImageThumb.min() vmaxThumb = npaImageThumb.max() NPAImageFloatThumb = (npaImageThumb.astype(float) - vminThumb) / (vmax - vminThumb) NPAImageInt = (255.0 * (NPAImageFloat ** 0.3)).astype("uint8") NPAImageIntThumb = (255.0 * (NPAImageFloatThumb ** 0.3)).astype("uint8") pilImage = Image.fromarray(NPAImageInt, 'L') pilImageThumb = Image.fromarray(NPAImageIntThumb, 'L') # For ISPyB we use for the moment only 1024x1024 and 256x256 pilImage.thumbnail((1024, 1024), Image.ANTIALIAS) pilImageThumb.thumbnail((256, 256), Image.ANTIALIAS) pilImage = ImageOps.invert(pilImage) pilImageThumb = ImageOps.invert(pilImageThumb) self.synchronizeOn() if 1024 * 1024 > ImageFile.MAXBLOCK: ImageFile.MAXBLOCK = 1024 * 1024 pilImage.save(self.strOutputPath, "JPEG", quality=50, optimize=True) pilImageThumb.save(self.strOutputPathThumb, "JPEG", quality=85, optimize=True) self.synchronizeOff()
def ConvertToBitifiedImage(file_location, thumbnail_width=settings.THUMBNAIL_WIDTH, final_width=settings.FINAL_WIDTH, bit_depth=settings.BIT_DEPTH): """Loads image from filename, generates bitified Image and returns it.""" # Load image from file location image = Image.open(file_location).convert('RGB') # If image is JPG/GIF perform extra processing to image if image.format == 'JPG': image = ImageOps.autocontrast(image) elif image.format == 'GIF': # Need to equalize to change gif to something that can be converted. image = ImageOps.equalize(image) # Blur image and reduce number of colors to bit_depth image = image.convert('P', palette=Image.ADAPTIVE, colors=bit_depth).convert('RGB') processed_image = image.copy() # Keep only most common color in large area processed_image = processed_image.filter(ImageFilter.BLUR) # Low-pass filter for x in xrange(processed_image.size[0]): for y in xrange(processed_image.size[1]): r, g, b = processed_image.getpixel((x, y)) if r < 50 and g < 50 and b < 50: processed_image.putpixel((x, y), (0, 0, 0)) else: processed_image.putpixel((x, y), (r, g, b)) # Set final width to at most final_width width, height = processed_image.size final_width = min(width, final_width) # Add border to image before shrinking processed_image = AddBorderToImage(processed_image) thumbnail_size = thumbnail_width, thumbnail_width * height/width final_size = final_width, final_width * height/width # Shrink image while keeping aspect ratio processed_image.thumbnail(thumbnail_size, Image.ADAPTIVE) # Resize back, resulting in pixelized image processed_image = processed_image.resize(final_size, Image.NEAREST) # Back to RGB format processed_image = processed_image.convert('RGB', palette=Image.ADAPTIVE, colors=bit_depth) # Add a random quote to the image processed_image = AddRandomTextToImage(processed_image) return processed_image
def _derotationTest(self, imageName): image = samples.getSample("algorithmTests", imageName)[0] inverted = ImageOps.invert(image.convert("L")) before = derotate._getAngle(inverted) derotated = derotate.derotate(image) invertedDerotated = ImageOps.invert(derotated) after = derotate._getAngle(invertedDerotated) self.assertLessEqual(abs(after), abs(before)) self.assertLessEqual(abs(after), 10.0)
def threshold(img, thresh): """Threshold an image""" pilIMG1 = Image.fromarray(img) pilInverted1 = ImageOps.invert(pilIMG1) inverted = numpy.asarray(pilInverted1) r, t = cv2.threshold(inverted, thresh, 0, type=cv.CV_THRESH_TOZERO) pilIMG2 = Image.fromarray(t) pilInverted2 = ImageOps.invert(pilIMG2) thresholded = numpy.asarray(pilInverted2) return thresholded
def __call__(self, img_ref): img = img_ref.get_image() if img.mode == '1': img = ImageOps.grayscale(img) elif img.mode != 'L': return img_ref h = img.histogram() if sum(h[:64]) < img.size[0] * img.size[1] / 2: return img_ref img = ImageOps.invert(img) return ImageRef(img)
def draw_histogram(pixbuf, height=170, fill=170, text=True): """Draw a histogram from <pixbuf> and return it as another pixbuf. The returned prixbuf will be 262x<height> px. The value of <fill> determines the colour intensity of the filled graphs, valid values are between 0 and 255. If <text> is True a label with the maximum pixel value will be added to one corner. """ im = Image.new('RGB', (258, height - 4), (30, 30, 30)) hist_data = image.pixbuf_to_pil(pixbuf).histogram() maximum = max(hist_data[:768] + [1]) y_scale = float(height - 6) / maximum r = [int(hist_data[n] * y_scale) for n in xrange(256)] g = [int(hist_data[n] * y_scale) for n in xrange(256, 512)] b = [int(hist_data[n] * y_scale) for n in xrange(512, 768)] im_data = im.getdata() # Draw the filling colours for x in xrange(256): for y in xrange(1, max(r[x], g[x], b[x]) + 1): r_px = y <= r[x] and fill or 0 g_px = y <= g[x] and fill or 0 b_px = y <= b[x] and fill or 0 im_data.putpixel((x + 1, height - 5 - y), (r_px, g_px, b_px)) # Draw the outlines for x in xrange(1, 256): for y in range(r[x-1] + 1, r[x] + 1) + [r[x]] * (r[x] != 0): r_px, g_px, b_px = im_data.getpixel((x + 1, height - 5 - y)) im_data.putpixel((x + 1, height - 5 - y), (255, g_px, b_px)) for y in range(r[x] + 1, r[x-1] + 1): r_px, g_px, b_px = im_data.getpixel((x, height - 5 - y)) im_data.putpixel((x, height - 5 - y), (255, g_px, b_px)) for y in range(g[x-1] + 1, g[x] + 1) + [g[x]] * (g[x] != 0): r_px, g_px, b_px = im_data.getpixel((x + 1, height - 5 - y)) im_data.putpixel((x + 1, height - 5 - y), (r_px, 255, b_px)) for y in range(g[x] + 1, g[x-1] + 1): r_px, g_px, b_px = im_data.getpixel((x, height - 5 - y)) im_data.putpixel((x, height - 5 - y), (r_px, 255, b_px)) for y in range(b[x-1] + 1, b[x] + 1) + [b[x]] * (b[x] != 0): r_px, g_px, b_px = im_data.getpixel((x + 1, height - 5 - y)) im_data.putpixel((x + 1, height - 5 - y), (r_px, g_px, 255)) for y in range(b[x] + 1, b[x-1] + 1): r_px, g_px, b_px = im_data.getpixel((x, height - 5 - y)) im_data.putpixel((x, height - 5 - y), (r_px, g_px, 255)) if text: maxstr = 'max: ' + str(maximum) draw = ImageDraw.Draw(im) draw.rectangle((0, 0, len(maxstr) * 6 + 2, 10), fill=(30, 30, 30)) draw.text((2, 0), maxstr, fill=(255, 255, 255)) im = ImageOps.expand(im, 1, (80, 80, 80)) im = ImageOps.expand(im, 1, (0, 0, 0)) return image.pil_to_pixbuf(im)
def threshold(img, thresh): """Threshold an image""" pilIMG1 = Image.fromarray(img); pilInverted1 = ImageOps.invert(pilIMG1); inverted = np.asarray(pilInverted1); r, t = cv2.threshold(inverted, thresh, 0, type=cv.CV_THRESH_TOZERO); pilIMG2 = Image.fromarray(t); pilInverted2 = ImageOps.invert(pilIMG2); thresholded = np.asarray(pilInverted2); return thresholded;
def resizeImage(self, buffer_filepath, local_filepath, params, cropped_image = False): image = Image.open(buffer_filepath) width, height = image.size imgData = { "width" : width, "height": height } need_resize = False createSmallItemSpell = False if "type_of_form" in params and params['type_of_form'] == "create_artwork": checkWidth = self.core.MAX_ARTWORK_WIDTH checkHeight = self.core.MAX_ARTWORK_HEIGHT elif "type_of_form" in params and (params['type_of_form'] == "create_item" or params['type_of_form'] == "create_spell"): checkWidth = self.core.MAX_ITEM_SPELL_WIDTH checkHeight = self.core.MAX_ITEM_SPELL_HEIGHT createSmallItemSpell = True else: checkWidth = self.core.MAX_AVA_WIDTH checkHeight = self.core.MAX_AVA_HEIGHT if width > checkWidth: width = checkWidth need_resize = True if height > checkHeight: height = checkHeight need_resize = True #need_resize = False if need_resize: if params['type_of_form'] == "create_artwork": thumb = ImageOps.fit(cropped_image, (self.core.THUMB_ARTWORK_WIDTH, self.core.THUMB_ARTWORK_HEIGHT), Image.ANTIALIAS) else: thumb = ImageOps.fit(cropped_image, (width,height), Image.ANTIALIAS) thumb.save(local_filepath+"_fit.png", "PNG") elif params['type_of_form'] == "create_artwork": thumb = ImageOps.fit(cropped_image, (self.core.THUMB_ARTWORK_WIDTH, self.core.THUMB_ARTWORK_HEIGHT), Image.ANTIALIAS) thumb.save(local_filepath+"_fit.png", "PNG") else: image.save(local_filepath+"_fit.png", "PNG") if createSmallItemSpell: thumb = ImageOps.fit(cropped_image, (self.core.THUMB_ITEM_SPELL_WIDTH, self.core.THUMB_ITEM_SPELL_HEIGHT), Image.ANTIALIAS) thumb_local_filpath = local_filepath+"_thumb.png" thumb.save(thumb_local_filpath,"PNG") return imgData
import os import Image, ImageOps """ This parser requires ImageMagick (http://www.imagemagick.org/) library. You can install it by typing: sudo apt-get install imagemagick """ commands =[\ 'wget http://www.ini.uzh.ch/~acardona/data/membranes-neurites-glia.tif.tar.bz2 -O atlases/tem/src/membranes-neurites-glia.tif.tar.bz2', 'bunzip2 -f atlases/tem/src/membranes-neurites-glia.tif.tar.bz2', 'tar -xvvf atlases/tem/src/membranes-neurites-glia.tif.tar -C atlases/tem/src/', 'convert atlases/tem/src/membranes-neurites-glia.tif -level 0,255 -depth 8 -type grayscale atlases/tem/src/membranes-neurites-glia.png'] map(os.system, commands) for index in range(30): filename = 'atlases/tem/src/membranes-neurites-glia-%d.png' % index frame = Image.open(filename) frame = ImageOps.expand(frame, border=4, fill=168) frame.save(filename)
def resize_image_fit(img, target_width, target_height, dir): img = ImageOps.fit(img, (target_width, target_height), Image.ANTIALIAS) if not os.path.exists(dir + fname): print " + generated new image", dir + fname img.save(dir + fname)
##PIL_IMAGE import PIL import Image import io import ImageOps import ImageFilter image = Image.open("Cartilagini.png") a=ImageOps.solarize(image, threshold=128) a.show() bits=2 b=ImageOps.posterize(image, bits) b.show() imout1 = image.filter(ImageFilter.EDGE_ENHANCE) imout1.show() imout2 = image.filter(ImageFilter.EDGE_ENHANCE_MORE) imout2.show() imout3 = image.filter(ImageFilter.EMBOSS) imout3.show() imout4 = image.filter(ImageFilter.FIND_EDGES)
def counting(c_std, a_std, imageFile): image_list = [imageFile] c_std = float(c_std) if image_list[0][-3:] == 'tif': for f, filename in enumerate(image_list): subprocess.call(["convert", filename, filename + '.png']) image_list[f] = filename + '.png' output_filename_hash = (datetime.datetime.now().minute * 60 + datetime.datetime.now().second) images = [ scipy.misc.imread(filename).astype(np.uint16) for filename in image_list ] #correlation_matrix = np.array([[-1, -1, -1, -1, -1], # [-1, -1, -1, -1, -1], # [-1, -1, 24, -1, -1], # [-1, -1, -1, -1, -1], # [-1, -1, -1, -1, -1]]) correlation_matrix = np.array([[-5935, -5935, -5935, -5935, -5935], [-5935, 8027, 8027, 8027, -5935], [-5935, 8027, 30742, 8027, -5935], [-5935, 8027, 8027, 8027, -5935], [-5935, -5935, -5935, -5935, -5935]]) median_diameter = 5 local_max = 3 #c_std = 1 processed_images = [np.copy(image).astype(np.int64) for image in images] processed_images = \ [np.subtract(image, np.minimum(spf.median_filter(image, median_diameter), image)) for image in images] processed_images = \ [np.maximum(scipy.signal.correlate(image, correlation_matrix, mode='same'), np.zeros_like(image)).astype(np.int64) for image in processed_images] thresholded_images = [ image > np.mean(image) + c_std * np.std(image) #images[i] > np.mean(images[i]) + a_std * np.std(images[i]) #images[i] > a_std for i, image in enumerate(processed_images) ] for i, mask in enumerate(thresholded_images): for (h, w), valid in np.ndenumerate(mask): if valid: local_slice = \ np.copy(processed_images[i][h - local_max:h + local_max + 1, w - local_max:w + local_max + 1]) if (h + local_max >= mask.shape[0] or w + local_max >= mask.shape[1] or h - local_max < 0 or w - local_max < 0): mask[h, w] = False continue local_slice[local_max, local_max] = 0 if np.amax(local_slice) >= processed_images[i][h, w]: mask[h, w] = False size = 4 for i, image in enumerate(images): i_std = np.std(image) i_median = np.median(image) - i_std i_max = np.amax(image) for (h, w), value in np.ndenumerate(image): if image[h, w] > i_median: image[h, w] = int( np.around( math.sqrt(image[h, w] - i_median) / math.sqrt(i_max - i_median) * float(2**8 - 1))) else: image[h, w] = 0 output_images = [ ImageOps.colorize( Image.fromstring('L', image.shape, image.astype(np.uint8)), (0, 0, 0), (255, 255, 255)) for image in images ] for i, image in enumerate(images): for (h, w), value in np.ndenumerate(image): if thresholded_images[i][h, w]: box = ((w - size, h - size), (w + size, h + size)) draw = ImageDraw.Draw(output_images[i]) draw.rectangle(box, fill=None, outline='blue') # Editing the output file name; Will have the same as the filename + png [ image.save( str(i).zfill(int(np.ceil(math.log(len(output_images), 10)))) + ' SIMPLE ' + str(output_filename_hash) + '.png') for i, image in enumerate(output_images) ] for i, image in enumerate(thresholded_images): print( str(i).zfill(int(np.ceil(math.log(len(thresholded_images), 10)))) + ' ' + str(np.sum(np.sum(image))))
def move(delta, face_ind=0, run_model=False): global current, image_list if not (0 <= current + delta < len(image_list)): tkMessageBox.showinfo('End', 'No more image.') return current += delta orig_img = Image.open(image_list[current]) orig_img = np.array(ImageOps.fit(orig_img, size, Image.ANTIALIAS)) # ready for processing with model if run_model: ################################################################################# print("Running Facial Landmarks for ", image_list[current]) def create_flat_list(list, ind): o = [] if len(list) == 0: print("No face detected.") fields = list[0].keys() for f in fields: o.append(list[ind][f]) flat_list = np.asarray([item for sublist in o for item in sublist]) return flat_list # extract facial landmarks face_landmarks_list = face_recognition.face_landmarks(orig_img) flfl = create_flat_list(face_landmarks_list, face_ind) # create binary image bw_img = np.zeros(orig_img.shape[0:2]) bw_img[tuple(np.vstack((flfl[:, 1], flfl[:, 0])))] = 1 # [255, 0, 0] bw_img = np.array(ndimage.grey_dilation(bw_img, size=(dilation_size, dilation_size)), dtype=np.uint8) bw_img = cv2.cvtColor(bw_img, cv.CV_GRAY2RGB) * 255 f_img = bw_img#np.ones((256,256, 3), dtype=np.uint8) * 255 print("Finished face recognition.") ################################################################################# print("Running Generator for ", image_list[current]) pre = (f_img.astype(np.float32) / 255) * 2 - 1 # ! important or the output will be corrupted feed[b] = np.reshape(pre, (1, size[0], size[1], 3)) r = sess.run(op, feed) gen_img = np.reshape(r, (size[0], size[1], 3)).astype(np.uint8) print("Finished generation.") ################################################################################# else: gen_img = np.zeros((size)) f_img = np.zeros((size)) # prepare for visualization in GUI orig_img = Image.fromarray(orig_img) gen_img = Image.fromarray(gen_img) f_img = Image.fromarray(f_img) orig_img = ImageTk.PhotoImage(orig_img) gen_img = ImageTk.PhotoImage(gen_img) f_img = ImageTk.PhotoImage(f_img) label['text'] = "Original" label['image'] = orig_img label.photo = orig_img label_gen["text"] = "Generated" label_gen["image"] = gen_img label_gen.photo = gen_img label_f["text"] = "Facial Landmarks" label_f["image"] = f_img label_f.photo = f_img
def horizontal_symmetry(digit, features, prefix=''): width,height = digit.image.size first_half = numpy.array(digit.image.crop((0, 0, width, height/2)).getdata()) second_half = numpy.array(ImageOps.flip(digit.image.crop((0, height/2, width, height))).getdata()) second_half = second_half[:len(first_half)] features[prefix+'horizontal_symmetry'] = numpy.linalg.norm(first_half-second_half)
im1.save(prefix+'sh235_4096sq_WISE_mosaic.png') #rgb_pil = ((1-rgb[:,:,:3])*(2**8)) #rgb_pil -= (256*rgb[:,:,3])[:,:,newaxis] #rgb_pil[rgb_pil>255] = 255 #rgb_pil = rgb_pil.astype('uint8') #im1 = PIL.Image.fromarray(rgb_pil) #im1.save(prefix+'sh235_4096sq_WISE_mosaic_try2.png') print "Saving WISE mosaic with white bg ",time.time()-t0 wbackground = PIL.Image.new("RGB", im1.size, (255, 255, 255)) wbackground.paste(im1, mask=im1.split()[3]) wbackground.save(prefix+'sh235_4096sq_WISE_mosaic_whitebg.png') kbackground = PIL.Image.new("RGB", im1.size, (0, 0, 0)) kbackground.paste(im1, mask=im1.split()[3]) print "Saving WISE mosaic with black bg ",time.time()-t0 kbackground.save(prefix+'sh235_4096sq_WISE_mosaic_blackbg.png') kbackground_contrast = ImageOps.autocontrast(kbackground) kbackground_contrast.save(prefix+'sh235_4096sq_WISE_mosaic_blackbg_contrast.png') kbackground_bright = ImageEnhance.Brightness(kbackground_contrast).enhance(1.5) kbackground_bright.save(prefix+'sh235_4096sq_WISE_mosaic_blackbg_contrast_bright.png') print "doing Bolocam PIL stuff ",time.time()-t0 v2pil = (v2img*255).astype('uint8')[pilslice,:,:] v2pil = v2pil[::-1,:,:] boloim = PIL.Image.fromarray(v2pil) boloim.save(prefix+'sh235_4096sq_bolo.png') kbackground.paste(boloim, mask=boloim.split()[3]) print "Saving Bolocam + WISE mosaic with black bg (PIL) ",time.time()-t0 kbackground.save(prefix+'sh235_4096sq_WISE_bolo_mosaic_blackbg.png') print "Done ",time.time()-t0
def imagetogcode(image, f): img = ImageOps.invert(image) width, height = img.size f.write("; Image pixel size: " + str(width) + "x" + str(height) + "\n") f.write("M649 S11 B2 D0 R0.0846 F6000\nG28\nG0 X70 Y45 F6000\n") pixels = list(img.getdata()) pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)] forward = True # def get_chunks(arr, chunk_size = 51): def get_chunks(arr, chunk_size=51): chunks = [ arr[start:start + chunk_size] for start in range(0, len(arr), chunk_size) ] return chunks # return the last pixel that holds data. def last_in_list(arr): end = 0 for i in range(len(arr)): if (arr[i] > 0): end = i return end # return the last pixel that holds data. def first_in_list(arr): end = 0 for i in range(len(arr)): if (arr[i] == 0): end = i if (arr[i] > 0): break return end first = True row = pixels[::-1] previousRight = 99999999999 previousLeft = 0 firstRow = True for index, rowData in enumerate(row): print "Line " + str(index + 1) + " =" #print rowData splitRight = 0 splitLeft = 0 if (index + 1 < len(row)): # Determine where to split the lines. ################################################## #If the left most pixel of the next row is earlier than the current row, then extend. if (first_in_list(row[index + 1]) > first_in_list(rowData)): splitLeft = first_in_list(rowData) else: splitLeft = first_in_list(row[index + 1]) #If the end pixel of the next line is later than the current line, extend. if (last_in_list(row[index + 1]) > last_in_list(rowData)): splitRight = last_in_list(row[index + 1]) else: splitRight = last_in_list(rowData) print "Prior Left cut = " + str( splitLeft) + " Right Cut == " + str(splitRight) else: splitLeft = first_in_list(rowData) splitRight = last_in_list(rowData) #Positive direction if forward: print "Forward!" #Split the right side. ########################################### #Don't split more than the start of the last row as we print in reverse for alternate lines splitLeft = previousLeft previousRight = splitRight #Negative direction else: print "Backward!" #Split the left side. ########################################### #Don't split more than the end of the last row as we print in reverse for alternate lines splitRight = previousRight previousLeft = splitLeft #Exception to the rule : Don't split the left of the first row. if (firstRow): splitLeft = (previousLeft) firstRow = False print "After : Left cut = " + str(splitLeft) + " Right Cut == " + str( splitRight) row2 = rowData[(splitLeft + 1):(splitRight + 1)] print row2 #if(index == 5): # raise Exception('End') if not forward: result_row = row2[::-1] else: result_row = row2 for chunk in get_chunks(result_row, 51): if first: if forward: f.write("\nG7 $1 ") # f.write("G7 $1\nG7 ") else: f.write("\nG7 $0 ") # f.write("G7 $0\nG7 ") first = not first else: f.write("G7 ") b64 = base64.b64encode("".join(chr(y) for y in chunk)) f.write("L" + str(len(b64)) + " ") f.write("D" + b64 + "\n") forward = not forward first = not first f.write("M5 \n")
def cropped_thumbnail(image, size): return ImageOps.fit(image, size, Image.ANTIALIAS)
#input argument check if (len(sys.argv) != 2): print "Usage: python bmp2array.py <Image.bmp>" sys.exit(1) else: inputImage = Image.open(sys.argv[1], 'r') #convert the image to gray scale image, 8 bit per pixel inputImage = inputImage.convert('L') #resize the image to 512 by 512 pixels inputImage = inputImage.resize((512, 512), Image.ANTIALIAS) #create 4-pixel border inputImage = ImageOps.expand(inputImage, border=4, fill='black') #convert image to pixel array imageArray = numpy.array(inputImage) #inputArray = open('inputArray','w') #inputArray.write(imageArray) #inputArray.close() #open the pixel array file to write to outputArray = open('pixelArray', 'w') row_number = 0
def makepilimage(self, scale="log", negative=False): """ Makes a PIL image out of the array, respecting the z1 and z2 cutoffs. By default we use a log scaling identical to iraf's, and produce an image of mode "L", i.e. grayscale. But some drawings or colourscales will change the mode to "RGB" later, if you choose your own colours. If you choose scale = "clog" or "clin", you get hue values (aka rainbow colours). """ if scale == "log" or scale == "lin": self.negative = negative numpyarrayshape = self.numpyarray.shape calcarray = self.numpyarray.copy() #calcarray.ravel() # does not change in place in fact ! calcarray = calcarray.clip(min=self.z1, max=self.z2) if scale == "log": calcarray = np.array( map(lambda x: loggray(x, self.z1, self.z2), calcarray)) else: calcarray = np.array( map(lambda x: lingray(x, self.z1, self.z2), calcarray)) calcarray.shape = numpyarrayshape bwarray = np.zeros(numpyarrayshape, dtype=np.uint8) calcarray.round(out=bwarray) if negative: if self.verbose: print "Using negative scale" bwarray = 255 - bwarray if self.verbose: print "PIL range : [%i, %i]" % (np.min(bwarray), np.max(bwarray)) # We flip it so that (0, 0) is back in the bottom left corner as in ds9 # We do this here, so that you can write on the image from left to right :-) self.pilimage = imop.flip(im.fromarray(bwarray.transpose())) if self.verbose: print "PIL image made with scale : %s" % scale return 0 if scale == "clog" or scale == "clin": """ rainbow ! Algorithm for HSV to RGB from http://www.cs.rit.edu/~ncs/color/t_convert.html, by Eugene Vishnevsky Same stuff then for f2n in C h is from 0 to 360 (hue) s from 0 to 1 (saturation) v from 0 to 1 (brightness) """ self.negative = False calcarray = self.numpyarray.transpose() if scale == "clin": calcarray = (calcarray.clip(min=self.z1, max=self.z2) - self.z1) / (self.z2 - self.z1) # 0 to 1 if scale == "clog": calcarray = 10.0 + 990.0 * ( calcarray.clip(min=self.z1, max=self.z2) - self.z1) / ( self.z2 - self.z1) # 10 to 1000 calcarray = (np.log10(calcarray) - 1.0) * 0.5 # 0 to 1 #calcarray = calcarray * 359.0 # This is now our "hue value", 0 to 360 calcarray = (1.0 - calcarray ) * 300.0 # I limit this to not go into red again # The order of colours is Violet < Blue < Green < Yellow < Red # We prepare the output arrays rcalcarray = np.ones(calcarray.shape) gcalcarray = np.ones(calcarray.shape) bcalcarray = np.ones(calcarray.shape) h = calcarray / 60.0 # sector 0 to 5 i = np.floor(h).astype(np.int) v = 1.0 * np.ones(calcarray.shape) s = 1.0 * np.ones(calcarray.shape) f = h - i # factorial part of h, this is an array p = v * (1.0 - s) q = v * (1.0 - s * f) t = v * (1.0 - s * (1.0 - f)) # sector 0: indices = (i == 0) rcalcarray[indices] = 255.0 * v[indices] gcalcarray[indices] = 255.0 * t[indices] bcalcarray[indices] = 255.0 * p[indices] # sector 1: indices = (i == 1) rcalcarray[indices] = 255.0 * q[indices] gcalcarray[indices] = 255.0 * v[indices] bcalcarray[indices] = 255.0 * p[indices] # sector 2: indices = (i == 2) rcalcarray[indices] = 255.0 * p[indices] gcalcarray[indices] = 255.0 * v[indices] bcalcarray[indices] = 255.0 * t[indices] # sector 3: indices = (i == 3) rcalcarray[indices] = 255.0 * p[indices] gcalcarray[indices] = 255.0 * q[indices] bcalcarray[indices] = 255.0 * v[indices] # sector 4: indices = (i == 4) rcalcarray[indices] = 255.0 * t[indices] gcalcarray[indices] = 255.0 * p[indices] bcalcarray[indices] = 255.0 * v[indices] # sector 5: indices = (i == 5) rcalcarray[indices] = 255.0 * v[indices] gcalcarray[indices] = 255.0 * p[indices] bcalcarray[indices] = 255.0 * q[indices] rarray = np.zeros(calcarray.shape, dtype=np.uint8) garray = np.zeros(calcarray.shape, dtype=np.uint8) barray = np.zeros(calcarray.shape, dtype=np.uint8) rcalcarray.round(out=rarray) gcalcarray.round(out=garray) bcalcarray.round(out=barray) carray = np.dstack((rarray, garray, barray)) self.pilimage = imop.flip(im.fromarray(carray, "RGB")) if self.verbose: print "PIL image made with scale : %s" % scale return 0 raise RuntimeError, "I don't know your colourscale, choose lin log clin or clog !"
def getBoxImage(self, image): invert_im = ImageOps.invert(image) return invert_im.getbbox()
def send_file(request, id, size=settings.DEFAULT_IMAGE_SIZE): size = int(size) uploaded_file = get_object_or_404(UploadedFile, id=id) if uploaded_file.group and not uploaded_file.group in request.user.groups.all(): raise Http403 original_filename = settings.FILE_SERVE_ROOT + "originals/" + uploaded_file.file.name filetype = uploaded_file.content_type.split('/')[0] if filetype != "image": filename = original_filename else: filename = settings.FILE_SERVE_ROOT + "cache/" + uploaded_file.file.name + "/" + str(size) if not os.path.exists(filename): if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) try: import Image image = Image.open(original_filename) except ImportError: try: from PIL import Image image = Image.open(original_filename) except ImportError: raise ImportError('Cannot import the Python Image Library.') exif = pyexiv2.ImageMetadata(original_filename) exif.read() if 'Exif.Image.Orientation' in exif.exif_keys: orientation = exif['Exif.Image.Orientation'].value if orientation == 1: # Nothing pass elif orientation == 2: # Vertical Mirror image = image.transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 3: # Rotation 180 image = image.transpose(Image.ROTATE_180) elif orientation == 4: # Horizontal Mirror image = image.transpose(Image.FLIP_TOP_BOTTOM) elif orientation == 5: # Horizontal Mirror + Rotation 270 image = image.transpose(Image.FLIP_TOP_BOTTOM).transpose(Image.ROTATE_270) elif orientation == 6: # Rotation 270 image = image.transpose(Image.ROTATE_270) elif orientation == 7: # Vertical Mirror + Rotation 270 image = image.transpose(Image.FLIP_LEFT_RIGHT).transpose(Image.ROTATE_270) elif orientation == 8: # Rotation 90 image = image.transpose(Image.ROTATE_90) # normalize image mode if image.mode != 'RGB': image = image.convert('RGB') method = "crop" delete_exif_thumbnail = True if size == 1: width, height = 40, 40 elif size == 2: width, height = 100, 100 elif size == 3: width, height = 160, 160 elif size == 4: width, height = 220, 220 elif size == 5: if image.size[0] > image.size[1]: width, height = 280, 210 else: width, height = 210, 280 elif size == 6: if image.size[0] > image.size[1]: width, height = 340, 255 else: width, height = 255, 340 elif size == 7: if image.size[0] > image.size[1]: width, height = 400, 300 else: width, height = 300, 400 elif size == 8: if image.size[0] > image.size[1]: width, height = 460, 345 else: width, height = 345, 460 elif size == 9: if image.size[0] > image.size[1]: width, height = 520, 390 else: width, height = 390, 520 elif size == 10: if image.size[0] > image.size[1]: width, height = 580, 435 else: width, height = 435, 580 elif size == 11: if image.size[0] > image.size[1]: width, height = 640, 480 else: width, height = 480, 640 elif size == 0: width, height = 520, 520 method = "scale" delete_exif_thumbnail = False # use PIL methods to edit images if method == 'scale': image.thumbnail((width, height), Image.ANTIALIAS) image.save(filename, FORMAT, quality=QUALITY) elif method == 'crop': try: import ImageOps ImageOps.fit(image, (width, height), Image.ANTIALIAS).save( filename, FORMAT, quality=QUALITY) except ImportError: from PIL import ImageOps ImageOps.fit(image, (width, height), Image.ANTIALIAS).save( filename, FORMAT, quality=QUALITY) if exif: if delete_exif_thumbnail: # delete thumbnail before copy. the changed original is not saved. thumb = pyexiv2.exif.ExifThumbnail(exif) thumb.erase() new_file_exif = pyexiv2.ImageMetadata(filename) new_file_exif.read() # reset image orientation for new image exif.copy(new_file_exif) new_file_exif['Exif.Image.Orientation'] = 1 new_file_exif['Exif.Image.ExifImageWidth'] = width new_file_exif['Exif.Image.ExifImageHeight'] = height new_file_exif.write() f = open(filename, 'r') output = f.read() f.close() response = HttpResponse(content_type=uploaded_file.content_type) response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = 'filename=%s' % (uploaded_file.filename.encode('utf-8'),) response.write(output) return response
def sketch(img): edge_img = img.filter(ImageFilter.CONTOUR) return ImageOps.grayscale(edge_img)
def array2png(array, filename, ztrans="log", cutoffs=(None, None)): # You need to generate the pilimage first ! import ImageOps, AImage pil = makepilimage(AImage.Image(array.copy()), ztrans, cutoffs) flippilimage = ImageOps.flip(pil) flippilimage.save(filename, "PNG")
screenshot3 = photos.pick_image(show_albums=True) mode = console.alert('Create or Clean', 'Select a mode below.', 'Create Now', 'Clean First') if mode == 2: from Cleanbar import cleanbar cleanbar(screenshot1) cleanbar(screenshot2) cleanbar(screenshot3) # Creates final image console.clear() print "Creating final image..." background = Image.new('RGBA', (1850, 1275), (255, 255, 255, 255)) file1 = screenshot1.resize((545, 969), Image.ANTIALIAS) file2 = screenshot2.resize((700, 1245), Image.ANTIALIAS) file3 = screenshot3.resize((545, 969), Image.ANTIALIAS) file1 = ImageOps.expand(file1, border=1, fill='gray') file2 = ImageOps.expand(file2, border=1, fill='gray') file3 = ImageOps.expand(file3, border=1, fill='gray') background.paste(file1, (10, 138)) background.paste(file2, (575, 15)) background.paste(file3, (1295, 138)) console.hide_activity() background.show() print "\n\n Image created"
def vertical_symmetry(digit, features, prefix=''): width,height = digit.image.size first_half = numpy.array(digit.image.crop((0, 0, width/2, height)).getdata()) second_half = numpy.array(ImageOps.mirror(digit.image.crop((width/2, 0, width, height)).getdata())) second_half = second_half[:len(first_half)] features[prefix+'vertical_symmetry'] = numpy.linalg.norm(first_half-second_half)
def processImage(indir, filename, cam, master_image=None): global images_to_process logging.info("Starting processImage()") images_to_process = True # only for testing purposes try: infilepathfilename = inpath(indir, filename) thumbpathfilename = thumbpath(indir, filename) mediumpathfilename = mediumpath(indir, filename) logging.info("Processing %s" % (infilepathfilename)) thumbexists = os.path.exists(thumbpathfilename) mediumexists = os.path.exists(mediumpathfilename) cropped_img = None if not (thumbexists and mediumexists): img = None try: img = Image.open(infilepathfilename) except IOError, e: logging.error("Cannot open file %s: %s" % (infilepathfilename, repr(e))) if img: cropped_img = crop_image(img, cam.croparea) del img # close img if cropped_img == None: logging.error("Failed to crop image %s, croparea: %s" % (infilepathfilename, str(cam.croparea))) # crop failure is likely due to attempting to process the # incoming image while it is still being uploaded. Return from # processImage() here and leave image in incoming dir--don't # mark it "done" by moving it to the hires dir. When we get # around to processing this image again, it will probably work # correctly. However, if the image mod time is more than an # hour old, it's not likely to still be uploading, so assume # it's just broken and let the normal code move it to hires # so we don't try to process it again if os.path.getmtime(infilepathfilename) >= (time.time() - 3600): logging.info("Returning from processImage()" \ + ", leaving original image in place") return cropped_img if (not mediumexists) and (not cropped_img == None): cropped_img.thumbnail(mediumsize, Image.ANTIALIAS) try: cropped_img.save(mediumpathfilename, "JPEG") except IOError: logging.error("Cannot save mediumres image %s" % mediumpathfilename) if (not thumbexists) and (not cropped_img == None): try: cropped_img.thumbnail(thumbsize, Image.ANTIALIAS) except IOError: logging.error("Cannot make thumbnail %s" % thumbpathfilename) if master_image != None: #compare current image with Master and make a box around the change diff_image = ImageOps.posterize( ImageOps.grayscale( ImageChops.difference(master_image, cropped_img)), 1) rect = diff_image.getbbox() if rect != None: ImageDraw.Draw(cropped_img).rectangle(rect, outline="yellow", fill=None) try: cropped_img.save(thumbpathfilename, "JPEG") except IOError: logging.error("Cannot save thumbnail %s" % thumbpathfilename) # done processing, move raw file to storage, so we won't process it again. infilepathfilename = inpath(indir, filename) hirespathfilename = hirespath(indir, filename) shutil.move(infilepathfilename, hirespathfilename)
def sphereToPicture(sphere): picture = normalize(sphere) picture = ImageOps.colorize(picture, (10, 0, 100), (0, 256, 0)) picture = imageToPygame(picture) return picture
def Segmentacao(caminho, diretorio): # cria o direotorio novo para a captura try: os.stat('Imagens/Cortes/' + diretorio) except: os.mkdir('Imagens/Cortes/' + diretorio) imagem = cv2.imread(caminho) #le a imagem resultante do resultado anterior peb = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY) # tons de cinza _, segmentacao = cv2.threshold( peb, 150, 255, cv2.THRESH_BINARY_INV) # segmentacao threshold holding = cv2.getStructuringElement( cv2.MORPH_RECT, (1, 2)) #1 e 2 sao porporcoes de descoberta dilated = cv2.dilate(segmentacao, holding, iterations=2) #dilatacao dos resultados encontrados contornos, hierarchy = cv2.findContours( dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # gera array de contornos media = 0 b = 0 for cont in contornos: # para cada contorno gerado [x, y, w, h] = cv2.boundingRect(cont) #gera um retangulo da area dos contornos largimg, altimg = imagem.shape[:2] contorno = int(largimg / 110) corte = imagem[y:y + h, x:x + w] #gera a imagem de corte com margens de 3 e 4 px largura, altura = corte.shape[: 2] #pega a largura e altura da imagem de corte if altura == 0: #caso nao haja altura, se atribui 0,001 para evitar divisao por 0 altura = 0.001 proporcao = largura / altura #gera a proporcao entre largura e altura min = largimg / 15 if (largura >= TamanhoMinimo) and (largura <= TamanhoMaximo) and ( (proporcao >= Proporcao1 and proporcao <= Proporcao2) or (proporcao >= Proporcao3 and proporcao <= Proporcao4)): print(str(x + y) + ".jpg " + str(proporcao) + " " + str(largura) ) #printa a proporcao e largura da imagem de corte atual media = media + altura if largura > b: b = largura cv2.imwrite('Imagens/Cortes/' + diretorio + '/' + str(y + x) + '.jpg', corte) #salva imagem de corte imag = Image.open('Imagens/Cortes/' + diretorio + '/' + str(y + x) + '.jpg') img_borda = ImageOps.expand(imag, border=3, fill='white') img_borda.save('Imagens/Cortes/' + diretorio + '/' + str(y + x) + '.jpg') #cv2.rectangle(imagem,(x,y),(x+w,y+h),(255,0,255),2) cv2.imwrite(caminho, imagem) print(b)
def image_to_thumbnail(image): return ImageOps.fit(image, (size, size), Image.ANTIALIAS)
def normalize(image): image = image.filter(ImageFilter.BLUR) picture = ImageChops.blend(ImageOps.equalize(image), image, .5) return ImageChops.multiply(picture, picture)
def loadFile(self,fileName): self.image = Image.eval(ImageOps.grayscale(Image.open(fileName)), lambda a: 1 if a <128 else 0) x,y = self.image.size self.x = x self.y = y
src_file = 'lena.tif' #hozon image dst_file = 'lena2.tif' #patch size patch_size = (8, 8) #load dictionary V = np.load('Dictionaries.npy') #image read im = Image.open(src_file) #guresuke hennkann gray_im = ImageOps.grayscale(im) #output image syokika dst_array = np.zeros((gray_im.size[1], gray_im.size[0])) #image patch_size bunkatu to syori w = gray_im.size[0] - patch_size[0] h = gray_im.size[1] - patch_size[1] y = 0 while y <= h: x = 0 while x <= w: #patchsize kiritori box = (x, y, x + patch_size[0], y + patch_size[1]) crop_im = gray_im.crop(box)
import os import Image import ImageOps import numpy as np path = '/Users/oli/Dropbox/Photos/Sample Album/' imgs = os.listdir(path) # Creating images (fake only 3 real images) just for demonstration PIXELS = 96 X = np.zeros((100, 3, PIXELS, PIXELS), dtype='float32') y = np.zeros(100) for i in range(0, 100): d = i % 3 y[i] = d img = Image.open(path + imgs[d]) img = ImageOps.fit(img, (PIXELS, PIXELS), Image.ANTIALIAS) img = np.asarray(img, dtype='float32') / 255. img = img.transpose(2, 0, 1).reshape(3, PIXELS, PIXELS) X[i] = img net1 = NeuralNet( layers=[ ('input', layers.InputLayer), ('hidden1', layers.DenseLayer), ('hidden2', layers.DenseLayer), ('output', layers.DenseLayer), ], input_shape=( None, 3, PIXELS, PIXELS ), #None in the first axis indicates that the batch size can be set later hidden1_num_units=500,
def triangles(original, n=30, size=150, width=700, height=700, min_distance=70, opacity=220): original = original.convert('RGB') colours = util.get_dominant_colours(original, 8) colours_ordered = util.order_colours_by_brightness(colours) brightest_colour = list(random.choice(colours_ordered[:3])) brightest_colour.append(0) new = Image.new('RGBA', (width, height), tuple(brightest_colour)) draw = aggdraw.Draw(new) centres = [] def is_too_close(x, y): for centre in centres: if math.sqrt( math.pow(centre[0] - x, 2) + math.pow(centre[1] - y, 2)) < min_distance: return True return False for i in xrange(n): colour = tuple(colours[int(random.randint(0, len(colours) - 1))]) x = random.randint(size / 2, width - 1 - size / 2) y = random.randint(size / 2, height - 1 - size / 2) if is_too_close(x, y): continue centres.append((x, y)) brush = aggdraw.Brush(colour, opacity) points = get_triangle_path(x, y, size / 2, size / 2) draw.polygon(points, None, brush) draw.flush() brightest_colour = brightest_colour[0:3] texture = Image.open( os.path.dirname(os.path.abspath(__file__)) + '/' + 'assets/airbrush.png') texture = texture.convert('RGBA') r, g, b, a = texture.split() texture = ImageOps.grayscale(texture) texture = ImageOps.colorize(texture, (0, 0, 0), tuple(brightest_colour)) texture = texture.convert('RGBA') texture.putalpha(a) r, g, b, a = new.split() texture = texture.crop((0, 0, width, height)) texture_layer = Image.new('RGBA', (width, height), (0, 0, 0, 0)) texture_layer.paste(texture, mask=new) new.paste(texture_layer, mask=texture_layer) im = Image.new('RGB', (width, height), tuple(brightest_colour)) im.paste(new, mask=a) return im
def getSeatOne(): im = ImageOps.grayscale(ImageGrab.grab ((xPad+25,yPad+60,xPad+88,yPad+76))) a = array(im.getcolors())
# https://gist.github.com/752f2591ee2b3d0e702b # make an array of icons to act as a decision aid import Image, ImageChops, ImageDraw, ImageFont, ImageOps dimension = 64 dimension_vert = 92 n_horiz = 10 n_vert = 10 n_switch = 7 img = Image.open('green_icon.png') img = ImageOps.grayscale(img) img = img.resize((dimension, dimension_vert), Image.BILINEAR) #img_alt = ImageChops.invert(img) img_alt = Image.open('red_icon.png') img_alt = img_alt.resize((dimension, dimension_vert), Image.BILINEAR) blank_image = Image.new("RGB", (dimension * n_horiz, dimension_vert * (n_vert + 1)), "white") counter = n_horiz * n_vert for vert in range(n_vert): for hor in range(n_horiz): if counter > n_switch: blank_image.paste(img, (hor * dimension, vert * dimension_vert)) else: blank_image.paste(img_alt, (hor * dimension, vert * dimension_vert)) counter -= 1
def generate_thumb(img, thumb_size, format): """ Generates a thumbnail image and returns a ContentFile object with the thumbnail Parameters: =========== img File object thumb_size desired thumbnail size, ie: (200,120) format format of the original image ('jpeg','gif','png',...) (this format will be used for the generated thumbnail, too) """ img.seek(0) # see http://code.djangoproject.com/ticket/8222 for details image = Image.open(img) # Convert to RGB if necessary if image.mode not in ('L', 'RGB', 'RGBA'): image = image.convert('RGB') #comprobar que la imagen no es mas alta que ancha #ancho, alto = image.size #if alto > ancho: # thumb_h, thumb_w = thumb_size #else: # thumb_w, thumb_h = thumb_size # get size thumb_w, thumb_h = thumb_size # If you want to generate a square thumbnail if thumb_w == thumb_h: # quad xsize, ysize = image.size # get minimum size minsize = min(xsize, ysize) # largest square possible in the image xnewsize = (xsize - minsize) / 2 ynewsize = (ysize - minsize) / 2 # crop it image2 = image.crop( (xnewsize, ynewsize, xsize - xnewsize, ysize - ynewsize)) # load is necessary after crop image2.load() # thumbnail of the cropped image (with ANTIALIAS to make it look better) image2.thumbnail(thumb_size, Image.ANTIALIAS) else: image2 = ImageOps.fit(image, thumb_size, Image.ANTIALIAS, 0, (0.5, 0.5)) # not quad #if image.size[0] > image.size[1]: # ancho = thumb_w # alto = (ancho*image.size[1])/image.size[0] #else: # #aqui ya he cambiado el valor del alto x el del alto en la linea 36 # alto = thumb_w # ancho = (alto*image.size[0])/image.size[1] #image2 = image #image2 = image2.resize((ancho, alto), Image.ANTIALIAS) io = cStringIO.StringIO() # PNG and GIF are the same, JPG is JPEG if format.upper() == 'JPG': format = 'JPEG' image2.save(io, format) return ContentFile(io.getvalue())
return 5 + ulpaste[1] + im.size[1] - slotwidth * (i + 1) for i in xrange(slots): draw.text((ulpaste[0] - 6 * slotwidth, getrow(i)), "0x%08x" % (i * 0x02000000), fill="#444444", font=dpf) for row in xrange(32): txt = Image.new("L", (600, 60)) d = ImageDraw.Draw(txt) d.text((0, 0), "0x%08x" % (row * 0x00100000), fill=255, font=dpf) del d rtxt = txt.rotate(17.5, expand=1) fim.paste(ImageOps.colorize(rtxt, "#ffffff", "#444444"), (ulpaste[0] + (row * (p_per_col / 32) * pheight), ulpaste[1] - 4 * slotwidth), rtxt) del txt del rtxt #draw.text ((ulpaste[0] + 0x00011000 * p_per_col*pheight / (32*1024*1024), ulpaste[1] + 65*slotwidth), # "Code/Data", fill="#000000", font=dpf) #draw.text ((ulpaste[0] + 0x018C0000 * p_per_col*pheight / (32*1024*1024), ulpaste[1] + 65*slotwidth), # "Stack/Heap", fill="#000000", font=dpf) def writerow(i, str): draw.text((10 * slotwidth, getrow(i)), str, fill="#000000", font=dpf)