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 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 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 image_file_features(infile, cl_options): im = Image.open(infile) hist_features = {} if cl_options.histogram: hist_features = array_to_features(im.histogram(), 'pixhist_') if cl_options.equalize: im = ImageOps.grayscale( ImageOps.equalize(im) ) if cl_options.blur: im_blur = scipy.ndimage.gaussian_filter(im, sigma=cl_options.blur) im = Image.fromarray(numpy.uint8(im_blur)) # from numpy->Grayscale Image if cl_options.horiz_ema: # scale to be independent of image size ????? im_ema = horiz_exp_mov_avg(im, cl_options.horiz_ema) im = Image.fromarray(numpy.uint8(im_ema)) # from numpy->Grayscale Image if cl_options.thumb_size: thumb_size = (cl_options.thumb_size, cl_options.thumb_size) im.thumbnail(thumb_size, Image.ANTIALIAS) if cl_options.thumb_dir: basename = os.path.basename(infile).split('.')[0] thumb_file = cl_options.thumb_dir + '/' + basename + '.png' im.save(thumb_file, "png") pix_features = {} if cl_options.pixels: pix_values = im.getdata() # returns a 1-D/flattened sequence of pixel values pix_features = array_to_features(pix_values, 'pix_') return dict(pix_features.items() + hist_features.items())
def equalize(image): if isinstance(image, pil.Image): if image.mode in ("F"): return equalizearray(np.asarray(image)) elif image.mode in ("RBGA"): image = image.convert("RBG") return ImageOps.equalize(image) else: return equalizearray(image)
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 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 equalize(image, amount=100): image = imtools.convert_safe_mode(image) if imtools.has_alpha(image): equalized = imtools.remove_alpha(image) else: equalized = image equalized = ImageOps.equalize(equalized) if imtools.has_alpha(image): imtools.put_alpha(equalized, imtools.get_alpha(image)) if amount < 100: equalized = imtools.blend(image, equalized, amount / 100.0) return equalized
def PreProcess(im): im = NMode(im) im1 = ndimage.grey_erosion(im, size=(10, 10)) scipy.misc.imsave("eroded.jpg", im1) im1 = Image.open("eroded.jpg") im = ImageOps.equalize(im, 0) im = ImageChops.difference(im1, im) #print ("image height %d and width %d\n"%(imh,imw)) im = GBinarization(im) #binarize the image return im
def PreProcess(im): im=NMode(im) im1 = ndimage.grey_erosion(im, size=(10,10)) scipy.misc.imsave("eroded.jpg",im1) im1= Image.open("eroded.jpg") im=ImageOps.equalize(im,0) im=ImageChops.difference(im1, im) #print ("image height %d and width %d\n"%(imh,imw)) im=GBinarization(im)#binarize the image return im
def GenEqual(file, label): ''' Generate Equalization feature There is a bug: when the total pixel count less than 255,ImageOps.equalize take no effect ''' noext, ext = os.path.splitext(file) if(ext == '.png'): im = Image.open(file) im = im.convert('L') im = ImageOps.equalize(im) data = im.getdata() for pixel in data: outputFile.write(str(pixel)+' ') outputFile.write(str(label)+ '\n')
def GenEqual(file, label): ''' Generate Equalization feature There is a bug: when the total pixel count less than 255,ImageOps.equalize take no effect ''' noext, ext = os.path.splitext(file) if (ext == '.png'): im = Image.open(file) im = im.convert('L') im = ImageOps.equalize(im) data = im.getdata() for pixel in data: outputFile.write(str(pixel) + ' ') outputFile.write(str(label) + '\n')
def dem2img(self, path, file): # Source LIDAR DEM file source = path + file # Load the ASCII DEM into a numpy array arr = np.loadtxt(source, skiprows=6) # Convert the numpy array to a PIL image im = Image.fromarray(arr).convert('L') # Enhance the image im = ImageOps.equalize(im) im = ImageOps.autocontrast(im) # Begin building our color ramp palette = [] # Hue, Saturaction, Value # color space h = .67 s = 1 v = 1 step = h / 256.0 for i in range(256): rp, gp, bp = colorsys.hsv_to_rgb(h, s, v) r = int(rp * 255) g = int(gp * 255) b = int(bp * 255) palette.extend([r, g, b]) h -= step # Apply the palette to the image im.putpalette(palette) im = im.convert('RGB') # Output image file img_path = os.path.dirname(os.getcwd( )) + '/webGIS/static/showLidar/images/' + file.split('.')[0] + '.jpg' # Save the image im.save(img_path) image = '/static/showLidar/images/' + file.split('.')[0] + '.jpg' return image
def showResult(n,result, dims, k=2): i = Image.new("RGB", dims) i.putdata(result, int(255 / (k - 1))) i = ImageOps.equalize(i) new = pil_to_pygame_img(i) screen = pygame.display.get_surface() if not screen.get_width == dims[1]: x=dims[0] y=dims[1] initScreen(x,y) screen.blit(new,(0,0)) if pygame.font: font = pygame.font.Font(None, 36) ts = 'Rule ' + str(n) text = font.render(ts, 1, (255, 255, 10)) textpos = text.get_rect() textpos.centerx = screen.get_rect().centery screen.blit(text, textpos) pygame.display.flip()
def normalize(image): image = image.filter(ImageFilter.BLUR) picture = ImageChops.blend(ImageOps.equalize(image), image, .5) return ImageChops.multiply(picture, picture)
import colorsys # Source LIDAR DEM file source = "lidar.asc" # Output image file target = "lidar.bmp" # Load the ASCII DEM into a numpy array arr = np.loadtxt(source, skiprows=6) # Convert the numpy array to a PIL image im = Image.fromarray(arr).convert('L') # Enhance the image im = ImageOps.equalize(im) im = ImageOps.autocontrast(im) # Begin building our color ramp palette = [] # Hue, Saturaction, Value # color space h = .67 s = 1 v = 1 # We'll step through colors from: # blue-green-yellow-orange-red. # Blue=low elevation, Red=high-elevation step = h / 256.0
def augment(self, image): return ImageOps.equalize(image)
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("EDPluginExecThumbnailv10.process") # try: # except Exception: # edfImage = EDF(self.inputFilename) # self.npaImage = edfImage.GetData(0) # Read the image using FABIO isRGB = False pilOutputImage = None if self.inputFilename is not None: try: fabioImage = openimage(self.inputFilename) self.npaImage = fabioImage.data except Exception: pilInputImage = Image.open(self.inputFilename) x, y = pilInputImage.size ImageFile.MAXBLOCK = x * y if pilInputImage.mode == "1": self.npaImage = numpy.asarray(pilInputImage).astype("uint8") isRGB = False elif pilInputImage.mode == "F": self.npaImage = numpy.asarray(pilInputImage) isRGB = False elif pilInputImage.mode == "L": self.npaImage = numpy.asarray(pilInputImage) isRGB = False elif pilInputImage.mode == "P": self.npaImage = numpy.asarray(pilInputImage.convert("RGB")) isRGB = True elif pilInputImage.mode == "RGB": self.npaImage = numpy.asarray(pilInputImage) isRGB = True elif pilInputImage.mode == "CMJK": self.npaImage = numpy.asarray(pilInputImage.convert("RGB")) isRGB = True dtype = self.npaImage.dtype NPAImageFloat = None # crop border if len(self.cropBorders) > 0: if len(self.cropBorders) == 1: crop0 = self.cropBorders[0] crop1 = self.cropBorders[0] else: crop0 = self.cropBorders[0] crop1 = self.cropBorders[1] if isRGB: self.npaImage = self.npaImage[crop0:-crop0, crop1:crop1, :] else: self.npaImage = self.npaImage[crop0:-crop0, crop1:crop1] # Set maxima and minima if (self.minLevelUnit is not None) or (self.maxLevelUnit is not None): sortedArray = self.npaImage.flatten() sortedArray.sort() if self.minLevel is not None: self.normalize = True if isRGB: EDVerbose.warning("It is not allowed to set Min with RGB data") else: if self.minLevelUnit in ["%", "percent"]: self.minLevel = sortedArray[int(round(float(self.minLevel) * sortedArray.size / 100.0))] if isinstance(self.npaImage[0, 0], int): self.npaImage = numpy.maximum(self.npaImage, int(self.minLevel) * numpy.ones_like(self.npaImage)) else: self.npaImage = numpy.maximum(self.npaImage, self.minLevel * numpy.ones_like(self.npaImage)) if self.maxLevel is not None: self.normalize = True if isRGB: EDVerbose.warning("It is not allowed to set Max with RGB data") else: if self.maxLevelUnit in ["%", "percent"]: self.maxLevel = sortedArray[int(round(float(self.maxLevel) * sortedArray.size / 100.0))] if isinstance(self.npaImage[0, 0], int): self.npaImage = numpy.minimum(self.npaImage, int(self.maxLevel) * numpy.ones_like(self.npaImage)) else: self.npaImage = numpy.minimum(self.npaImage, self.maxLevel * numpy.ones_like(self.npaImage)) # Scipy filters come here: if len(self.gaussianBlur) > 0: if len(self.gaussianBlur) == 1 : kernel = (self.gaussianBlur[0], self.gaussianBlur[0]) else: kernel = (self.gaussianBlur[0], self.gaussianBlur[1]) if isRGB: kernel = (kernel[0], kernel[1], 0) self.npaImage = scipy.ndimage.gaussian_filter(self.npaImage, kernel) if len(self.dilatation) > 0: if len(self.dilatation) == 1: kernel = (self.dilatation[0], self.dilatation[0]) else: kernel = (self.dilatation[0], self.dilatation[1]) if isRGB: kernel = (kernel[0], kernel[1], 0) self.npaImage = scipy.ndimage.morphology.grey_dilation(self.npaImage, kernel) #Normalization ; equalization if (self.normalize is True) or (self.equalize is True): if isRGB is True: self.npaImage = numpy.asarray(ImageOps.equalize(Image.fromarray(self.npaImage))) else: EDVerbose.DEBUG("EDPluginExecThumbnailv10: Normalization") vmin = self.npaImage.min() vmax = self.npaImage.max() NPAImageFloat = (self.npaImage.astype(numpy.float32) - float(vmin)) / (float(vmax) - float(vmin)) if (self.equalize == True): nbr_bins = 64 NPAImageFloatFlat = NPAImageFloat.flatten() imhist, bins = numpy.histogram(NPAImageFloatFlat, nbr_bins, normed=True) #get image histogram cdf = imhist.cumsum() #cumulative distribution function ncdf = cdf / cdf[-1] #normalized cumulative distribution function # print ncdf NPAImageFloat2Flat = numpy.interp(NPAImageFloatFlat, bins, [0] + ncdf.tolist()) NPAImageFloat = NPAImageFloat2Flat.reshape(NPAImageFloat.shape) EDVerbose.DEBUG("Equalize: min= %f, max= %f" % (NPAImageFloat.min(), NPAImageFloat.max())) #Gamma and logarithm scale if ((self.log is True) or (self.gamma != 1)) and (NPAImageFloat is None): # then we need the array in float if dtype == numpy.uint8: NPAImageFloat = self.npaImage.astype(numpy.float32) / 255.0 elif dtype == numpy.uint16: NPAImageFloat = self.npaImage.astype(numpy.float32) / 65535.0 else: NPAImageFloat = self.npaImage.astype(numpy.float32) if self.log is True: NPAImageFloat = numpy.log(1 - NPAImageFloat.min() + NPAImageFloat) vmin = NPAImageFloat.min() vmax = NPAImageFloat.max() NPAImageFloat = (NPAImageFloat - vmin) / (vmax - vmin) if self.gamma != 1: if dtype not in [numpy.uint8, numpy.uint16]: vmin = NPAImageFloat.min() vmax = NPAImageFloat.max() NPAImageFloat = (NPAImageFloat - vmin) / (vmax - vmin) NPAImageInt = (255.0 * (NPAImageFloat ** self.gamma)).astype("uint8") else: #if (self.gamma == 1): if NPAImageFloat is None: if dtype == numpy.uint8: NPAImageInt = self.npaImage elif dtype == numpy.uint16: NPAImageInt = (self.npaImage / 256).astype(numpy.uint8) else: #for float or a signed integer vmin = self.npaImage.min() vmax = self.npaImage.max() NPAImageInt = ((self.npaImage.astype(numpy.float32) - vmin) / (vmax - vmin) * 255.0).astype(numpy.uint8) else: vmin = NPAImageFloat.min() vmax = NPAImageFloat.max() EDVerbose.DEBUG("EDPluginExecThumbnailv10: NPAImageFloat => NPAImageInt min=%s max =%s" % (vmin, vmax)) NPAImageInt = ((NPAImageFloat - vmin) * 255.0 / (vmax - vmin)).astype(numpy.uint8) #COnversion back to PIL mode if isRGB is True: pilOutputImage = Image.fromarray(NPAImageInt, 'RGB') else: pilOutputImage = Image.fromarray(NPAImageInt, 'L') if (self.autocontrast is not None): pilOutputImage = ImageOps.autocontrast(pilOutputImage, self.autocontrast) if (self.width is not None) or (self.height is not None): if (self.width > 0) and (self.height > 0): if self.keepRatio is True: # PIL takes care of the ratio pilOutputImage.thumbnail((self.width, self.height), Image.ANTIALIAS) else: pilOutputImage = pilOutputImage.resize((self.width, self.height), Image.ANTIALIAS) else: if self.width is None: pilOutputImage.thumbnail((self.height, self.height), Image.ANTIALIAS) elif self.height is None: pilOutputImage.thumbnail((self.width, self.width), Image.ANTIALIAS) if self.invert == True: pilOutputImage = ImageOps.invert(pilOutputImage) if self.colorize == True: pilOutputImage.putpalette(EDPluginExecThumbnailv10.getPalette()) pilOutputImage = pilOutputImage.convert("RGB") self.synchronizeOn() if self.format == "jpg": self.width, self.height = pilOutputImage.size if self.width * self.height > ImageFile.MAXBLOCK: ImageFile.MAXBLOCK = self.width * self.height try: pilOutputImage.save(self.output, "JPEG", quality=85, optimize=True) except TypeError: pilOutputImage.save(self.output) else: pilOutputImage.save(self.output) self.synchronizeOff()
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("EDPluginExecThumbnailv10.process") # try: # except Exception: # edfImage = EDF(self.inputFilename) # self.npaImage = edfImage.GetData(0) # Read the image using FABIO isRGB = False pilOutputImage = None if self.inputFilename is not None: try: fabioImage = openimage(self.inputFilename) self.npaImage = fabioImage.data except Exception: pilInputImage = Image.open(self.inputFilename) x, y = pilInputImage.size ImageFile.MAXBLOCK = x * y if pilInputImage.mode == "1": self.npaImage = numpy.asarray(pilInputImage).astype( "uint8") isRGB = False elif pilInputImage.mode == "F": self.npaImage = numpy.asarray(pilInputImage) isRGB = False elif pilInputImage.mode == "L": self.npaImage = numpy.asarray(pilInputImage) isRGB = False elif pilInputImage.mode == "P": self.npaImage = numpy.asarray(pilInputImage.convert("RGB")) isRGB = True elif pilInputImage.mode == "RGB": self.npaImage = numpy.asarray(pilInputImage) isRGB = True elif pilInputImage.mode == "CMJK": self.npaImage = numpy.asarray(pilInputImage.convert("RGB")) isRGB = True dtype = self.npaImage.dtype NPAImageFloat = None # crop border if len(self.cropBorders) > 0: if len(self.cropBorders) == 1: crop0 = self.cropBorders[0] crop1 = self.cropBorders[0] else: crop0 = self.cropBorders[0] crop1 = self.cropBorders[1] if isRGB: self.npaImage = self.npaImage[crop0:-crop0, crop1:crop1, :] else: self.npaImage = self.npaImage[crop0:-crop0, crop1:crop1] # Set maxima and minima if (self.minLevelUnit is not None) or (self.maxLevelUnit is not None): sortedArray = self.npaImage.flatten() sortedArray.sort() if self.minLevel is not None: self.normalize = True if isRGB: EDVerbose.warning( "It is not allowed to set Min with RGB data") else: if self.minLevelUnit in ["%", "percent"]: self.minLevel = sortedArray[int( round(float(self.minLevel) * sortedArray.size / 100.0))] if isinstance(self.npaImage[0, 0], int): self.npaImage = numpy.maximum( self.npaImage, int(self.minLevel) * numpy.ones_like(self.npaImage)) else: self.npaImage = numpy.maximum( self.npaImage, self.minLevel * numpy.ones_like(self.npaImage)) if self.maxLevel is not None: self.normalize = True if isRGB: EDVerbose.warning( "It is not allowed to set Max with RGB data") else: if self.maxLevelUnit in ["%", "percent"]: self.maxLevel = sortedArray[int( round(float(self.maxLevel) * sortedArray.size / 100.0))] if isinstance(self.npaImage[0, 0], int): self.npaImage = numpy.minimum( self.npaImage, int(self.maxLevel) * numpy.ones_like(self.npaImage)) else: self.npaImage = numpy.minimum( self.npaImage, self.maxLevel * numpy.ones_like(self.npaImage)) # Scipy filters come here: if len(self.gaussianBlur) > 0: if len(self.gaussianBlur) == 1: kernel = (self.gaussianBlur[0], self.gaussianBlur[0]) else: kernel = (self.gaussianBlur[0], self.gaussianBlur[1]) if isRGB: kernel = (kernel[0], kernel[1], 0) self.npaImage = scipy.ndimage.gaussian_filter( self.npaImage, kernel) if len(self.dilatation) > 0: if len(self.dilatation) == 1: kernel = (self.dilatation[0], self.dilatation[0]) else: kernel = (self.dilatation[0], self.dilatation[1]) if isRGB: kernel = (kernel[0], kernel[1], 0) self.npaImage = scipy.ndimage.morphology.grey_dilation( self.npaImage, kernel) #Normalization ; equalization if (self.normalize is True) or (self.equalize is True): if isRGB is True: self.npaImage = numpy.asarray( ImageOps.equalize(Image.fromarray(self.npaImage))) else: EDVerbose.DEBUG("EDPluginExecThumbnailv10: Normalization") vmin = self.npaImage.min() vmax = self.npaImage.max() NPAImageFloat = (self.npaImage.astype(numpy.float32) - float(vmin)) / (float(vmax) - float(vmin)) if (self.equalize == True): nbr_bins = 64 NPAImageFloatFlat = NPAImageFloat.flatten() imhist, bins = numpy.histogram( NPAImageFloatFlat, nbr_bins, normed=True) #get image histogram cdf = imhist.cumsum() #cumulative distribution function ncdf = cdf / cdf[ -1] #normalized cumulative distribution function # print ncdf NPAImageFloat2Flat = numpy.interp(NPAImageFloatFlat, bins, [0] + ncdf.tolist()) NPAImageFloat = NPAImageFloat2Flat.reshape( NPAImageFloat.shape) EDVerbose.DEBUG("Equalize: min= %f, max= %f" % (NPAImageFloat.min(), NPAImageFloat.max())) #Gamma and logarithm scale if ((self.log is True) or (self.gamma != 1)) and ( NPAImageFloat is None): # then we need the array in float if dtype == numpy.uint8: NPAImageFloat = self.npaImage.astype(numpy.float32) / 255.0 elif dtype == numpy.uint16: NPAImageFloat = self.npaImage.astype(numpy.float32) / 65535.0 else: NPAImageFloat = self.npaImage.astype(numpy.float32) if self.log is True: NPAImageFloat = numpy.log(1 - NPAImageFloat.min() + NPAImageFloat) vmin = NPAImageFloat.min() vmax = NPAImageFloat.max() NPAImageFloat = (NPAImageFloat - vmin) / (vmax - vmin) if self.gamma != 1: if dtype not in [numpy.uint8, numpy.uint16]: vmin = NPAImageFloat.min() vmax = NPAImageFloat.max() NPAImageFloat = (NPAImageFloat - vmin) / (vmax - vmin) NPAImageInt = (255.0 * (NPAImageFloat**self.gamma)).astype("uint8") else: #if (self.gamma == 1): if NPAImageFloat is None: if dtype == numpy.uint8: NPAImageInt = self.npaImage elif dtype == numpy.uint16: NPAImageInt = (self.npaImage / 256).astype(numpy.uint8) else: #for float or a signed integer vmin = self.npaImage.min() vmax = self.npaImage.max() NPAImageInt = ( (self.npaImage.astype(numpy.float32) - vmin) / (vmax - vmin) * 255.0).astype(numpy.uint8) else: vmin = NPAImageFloat.min() vmax = NPAImageFloat.max() EDVerbose.DEBUG( "EDPluginExecThumbnailv10: NPAImageFloat => NPAImageInt min=%s max =%s" % (vmin, vmax)) NPAImageInt = ((NPAImageFloat - vmin) * 255.0 / (vmax - vmin)).astype(numpy.uint8) #COnversion back to PIL mode if isRGB is True: pilOutputImage = Image.fromarray(NPAImageInt, 'RGB') else: pilOutputImage = Image.fromarray(NPAImageInt, 'L') if (self.autocontrast is not None): pilOutputImage = ImageOps.autocontrast(pilOutputImage, self.autocontrast) if (self.width is not None) or (self.height is not None): if (self.width > 0) and (self.height > 0): if self.keepRatio is True: # PIL takes care of the ratio pilOutputImage.thumbnail((self.width, self.height), Image.ANTIALIAS) else: pilOutputImage = pilOutputImage.resize( (self.width, self.height), Image.ANTIALIAS) else: if self.width is None: pilOutputImage.thumbnail((self.height, self.height), Image.ANTIALIAS) elif self.height is None: pilOutputImage.thumbnail((self.width, self.width), Image.ANTIALIAS) if self.invert == True: pilOutputImage = ImageOps.invert(pilOutputImage) if self.colorize == True: pilOutputImage.putpalette(EDPluginExecThumbnailv10.getPalette()) pilOutputImage = pilOutputImage.convert("RGB") self.synchronizeOn() if self.format == "jpg": self.width, self.height = pilOutputImage.size if self.width * self.height > ImageFile.MAXBLOCK: ImageFile.MAXBLOCK = self.width * self.height try: pilOutputImage.save(self.output, "JPEG", quality=85, optimize=True) except TypeError: pilOutputImage.save(self.output) else: pilOutputImage.save(self.output) self.synchronizeOff()
def raster(result_img, filt, bbox = (-999,-999,999,9999), srs="EPSG:3857"): """ Applies various filters to image. """ for ff in filt: if ff.split(":") == [ff,]: if ff == "bw": result_img = result_img.convert("L") result_img = result_img.convert("RGBA") if ff == "contour": result_img = result_img.filter(ImageFilter.CONTOUR) if ff == "median": result_img = result_img.filter(ImageFilter.MedianFilter(5)) if ff == "blur": result_img = result_img.filter(ImageFilter.BLUR) if ff == "edge": result_img = result_img.filter(ImageFilter.EDGE_ENHANCE) if ff == "equalize": result_img = result_img.convert("RGB") result_img = ImageOps.equalize(result_img) result_img = result_img.convert("RGBA") if ff == "autocontrast": result_img = result_img.convert("RGB") result_img = ImageOps.autocontrast(result_img) result_img = result_img.convert("RGBA") if ff == "swaprb": ii = result_img.split() result_img = Image.merge("RGBA", (ii[2],ii[1],ii[0],ii[3])) else: ff, tts = ff.split(":") try: tt = float(tts) except: tt = 1 pass if ff == "brightness": enhancer = ImageEnhance.Brightness(result_img) result_img = enhancer.enhance(tt) if ff == "contrast": enhancer = ImageEnhance.Contrast(result_img) result_img = enhancer.enhance(tt) if ff == "sharpness": enhancer = ImageEnhance.Sharpness(result_img) result_img = enhancer.enhance(tt) if ff == "autocontrast": result_img = result_img.convert("RGB") result_img = ImageOps.autocontrast(result_img, tt) result_img = result_img.convert("RGBA") if ff == "fusion" and NUMPY_AVAILABLE: pix = numpy.array(result_img, dtype=int) a,b = result_img.size pan_img = getimg (bbox, srs, [b, a], config.layers[tts], datetime.datetime.now(), []) pan_img = pan_img.convert("L") print pix.dtype print pix[...,1].shape pan = numpy.array(pan_img) pix[...,0] = pix[...,0]*pan/(pix[...,0] + pix[...,1] + pix[...,2]) pix[...,1] = pix[...,1]*pan/(pix[...,0] + pix[...,1] + pix[...,2]) pix[...,2] = pix[...,2]*pan/(pix[...,0] + pix[...,1] + pix[...,2]) print pix.shape result_img = Image.fromarray(numpy.uint8(pix)) result_img = result_img.convert("RGBA") return result_img
#im8 = im.filter(ImageFilter.MedianFilter(size=3)) #im8.show() #mode filter #im8 = im.filter(ImageFilter.ModeFilter(size=3)) #im8.show() #EDGE_ENHANCEfilter #im8 = im.filter(ImageFilter.EDGE_ENHANCE) #im8.show() #greyscale the image im8 = ImageOps.grayscale(im) im8.show() #equalize the image im8 = ImageOps.equalize(im6) im8.show() #get image stats im_stat = ImageStat.Stat(im) print "stat.extrema = ", im_stat.extrema print "stat.count = ", im_stat.count print "stat.sum = ", im_stat.sum print "stat.sum2 = ", im_stat.sum2 print "stat.mean = ", im_stat.mean print "stat.median = ", im_stat.median print "stat.rms = ", im_stat.rms print "stat.var = ", im_stat.var print "stat.stddev = ", im_stat.stddev