def optimizeImage(self, gamma): if gamma < 0.1: gamma = self.gamma if gamma == 1.0: self.image = ImageOps.autocontrast(self.image) else: self.image = ImageOps.autocontrast(Image.eval(self.image, lambda a: 255 * (a / 255.) ** gamma))
def display_frame(self): ''' Displays the frame that the user selected via the slider ''' frame = self.slider.get() l, r = self.get_frame_location(self.left_cam) self.left_cam = self.left_cam[:l] + str(frame) + self.left_cam[r:] self.right_cam = self.right_cam[:l] + str(frame) + self.right_cam[r:] # load image self.left_frame = Image.open(self.left_cam) self.right_frame = Image.open(self.right_cam) self.left_frame = ImageOps.autocontrast(self.left_frame) self.right_frame = ImageOps.autocontrast(self.right_frame) left_frame_gif = ImageTk.PhotoImage(self.left_frame) right_frame_gif = ImageTk.PhotoImage(self.right_frame) # update image on gui self.left_image.configure(image = left_frame_gif) self.left_image.image = left_frame_gif self.right_image.configure(image = right_frame_gif) self.right_image.image = right_frame_gif self.frame_number.configure(text = "Current frame = " + self.left_cam[l:r]) self.frame_number.text = "Current frame = " + self.left_cam[l:r] self.master.update()
def get_frame_number(self, working_frame, testing_frame): ''' Determines if a user entered frame value is valid or if we should revert to a previously working frame. ''' try: # try new starting frame that user chose l, r = self.get_frame_location(self.left_cam) left_cam = self.left_cam[:l] + str(testing_frame) + self.left_cam[r:] right_cam = self.right_cam[:l] + str(testing_frame) + self.right_cam[r:] # try to open image self.left_frame = Image.open(left_cam) self.right_frame = Image.open(right_cam) left_frame = ImageOps.autocontrast(self.left_frame) right_frame = ImageOps.autocontrast(self.right_frame) left_frame_gif = ImageTk.PhotoImage(self.left_frame) right_frame_gif = ImageTk.PhotoImage(self.right_frame) return testing_frame except: # picture doesn't exist, start at previously working start frame self.start_frame = working_frame # get frame and filenames l, r = self.get_frame_location(self.left_cam) frame = self.start_frame self.left_cam = self.left_cam[:l] + str(working_frame) + self.left_cam[r:] self.right_cam = self.right_cam[:l] + str(working_frame) + self.right_cam[r:] return working_frame
def display_start_frame(self): frame = self.starting_frame.get() l, r = self.get_frame_location(self.left_cam) self.left_cam = self.left_cam[:l] + str(frame) + self.left_cam[r:] self.right_cam = self.right_cam[:l] + str(frame) + self.right_cam[r:] # load image try: self.left_frame = Image.open(self.left_cam) self.right_frame = Image.open(self.right_cam) self.left_frame = ImageOps.autocontrast(self.left_frame) self.right_frame = ImageOps.autocontrast(self.right_frame) left_frame_gif = ImageTk.PhotoImage(self.left_frame) right_frame_gif = ImageTk.PhotoImage(self.right_frame) # update image on gui self.left_image.configure(image = left_frame_gif) self.left_image.image = left_frame_gif self.right_image.configure(image = right_frame_gif) self.right_image.image = right_frame_gif self.frame_number.configure(text = "Current frame = " + self.left_cam[l:r]) self.frame_number.text = "Current frame = " + self.left_cam[l:r] self.master.update() except: showerror("Invalid start frame", "Please pick a valid start frame to display")
def checkImage( self, expected, actual, tol, msg ): '''Compare two image files. = INPUT VARIABLES - expected The filename of the expected image. - actual The filename of the actual image. - tol The tolerance (a unitless float). This is used to determinte the 'fuzziness' to use when comparing images. ''' from PIL import Image, ImageOps, ImageFilter # open the image files and remove the alpha channel (if it exists) expectedImage = Image.open( expected ).convert("RGB") actualImage = Image.open( actual ).convert("RGB") # normalize the images expectedImage = ImageOps.autocontrast( expectedImage, 2 ) actualImage = ImageOps.autocontrast( actualImage, 2 ) # compare the resulting image histogram functions h1 = expectedImage.histogram() h2 = actualImage.histogram() rms = math.sqrt( reduce( operator.add, map( lambda a,b: ( a - b )**2, h1, h2) ) / len( h1 ) ) diff = rms / 10000.0 msg += "\nError: Image files did not match.\n" \ " RMS Value: %22.15e\n" \ " Expected: %s\n" \ " Actual : %s\n" \ " Tolerance: %22.15e\n" % ( diff, expected, actual, tol ) self.assertLessEqual( diff, tol, msg )
def display_images(self): self.left_frame = Image.open(self.left_cam) self.left_frame = ImageOps.autocontrast(self.left_frame) self.right_frame = Image.open(self.right_cam) self.right_frame = ImageOps.autocontrast(self.right_frame) left_frame_gif = ImageTk.PhotoImage(self.left_frame) right_frame_gif = ImageTk.PhotoImage(self.right_frame)
def autocontrastImage(self): gamma = self.opt.gamma if gamma < 0.1: gamma = self.gamma if self.gamma != 1.0 and self.color: gamma = 1.0 if gamma == 1.0: self.image = ImageOps.autocontrast(self.image) else: self.image = ImageOps.autocontrast(Image.eval(self.image, lambda a: 255 * (a / 255.) ** gamma))
def method6(im): r,g,b,a = im.split() r = ImageOps.autocontrast(r, cutoff = 2) g = ImageOps.autocontrast(g, cutoff = 2) b = ImageOps.autocontrast(b, cutoff = 2) im3 = Image.merge('RGBA', (r,g,b,a)) enh3 = ImageEnhance.Sharpness(im3) im4 = enh3.enhance(2.0) im4.save("test_m6.tif")
def example6(): from PIL import Image from fractions import Fraction ship = Image.open("IPhone_Internals.jpg") w, h = ship.size slices = 12 #print(range(slices+1)) box = [ Fraction(i, slices) for i in range(slices+1)] #print(box) try: for i in range(slices): if i == slices: break for j in range(slices): if j == slices: break bounds = int(w*box[i]), int(h*box[j]), int(w*box[i+1]), int(h*box[j+i]) #print(bounds) except IndexError: pass logo = ship.crop(bounds) #logo.show() logo.save("IPhone_Internals_logo.jpg") # ImageEnhance, ImageFilter, ImageOps from PIL import ImageEnhance e = ImageEnhance.Contrast(logo) #e.enhance(2.0).show() #e.enhance(4.0).show() #e.enhance(8.0).show() e.enhance(8.0).save("LHD_Number_1.jpg") from PIL import ImageFilter #logo.filter(ImageFilter.EDGE_ENHANCE).show() e.enhance(8.0).filter(ImageFilter.EDGE_ENHANCE).save("LHD_Number_2.jpg") # combine p1 = e.enhance(8.0).filter(ImageFilter.ModeFilter(8)) #p1.filter(ImageFilter.EDGE_ENHANCE).show() p1.filter(ImageFilter.EDGE_ENHANCE).save("LHD_Number_2_1.jpg") # ImageOps from PIL import ImageOps ImageOps.autocontrast(logo).show() logo.show() ac = ImageEnhance.Contrast(ImageOps.autocontrast(logo)) ac.enhance(2.5).save("LHD_Number_3.jpg")
def load_image(self): """decode the image into a buffer""" self.image_data = Image.open(self.image_file) self.image_data = ImageOps.grayscale(self.image_data) if self.autocontrast: # may or may not improve the look of the transmitted spectrum self.image_data = ImageOps.autocontrast(self.image_data) if self.image_invert: # may or may not improve the look of the transmitted spectrum self.image_data = ImageOps.invert(self.image_data) if self.image_flip: # set to true for waterfalls that scroll from the top self.image_data = ImageOps.flip(self.image_data) (self.image_width, self.image_height) = self.image_data.size max_width = 4096.0 if self.image_width > max_width: scaling = max_width / self.image_width newsize = (int(self.image_width * scaling), int(self.image_height * scaling)) (self.image_width, self.image_height) = newsize self.image_data = self.image_data.resize(newsize) self.set_output_multiple(self.image_width) self.image_data = list(self.image_data.getdata()) if self.bt709_map: # scale brightness according to ITU-R BT.709 self.image_data = map( lambda x: x * 219 / 255 + 16, self.image_data) self.image_len = len(self.image_data) if self.repeatmode != 2: print "paint.image_source: %d bytes, %dpx width" % (self.image_len, self.image_width) self.line_num = 0
def main(): file1, file2 = sys.argv[1:1+2] print "compare images" print "image mode is greyscale (if images has another mode, the image will be converted)" im1 = Image.open(file1) im2 = Image.open(file2) print "image 1 : " , file1 , " , mode : ", im1.mode print "image 2 : " , file2 , " , mode : ", im2.mode if im1.mode != "L": im1 = im1.convert("L") if im2.mode != "L": im2 = im2.convert("L") diff = ImageChops.difference(im2,im1) diff = ImageOps.autocontrast(diff,0) diff.show("difference") im1.show("image1") im2.show("image2") save_path,f = os.path.split(file1) diff_path = save_path + "/diff.TIF" diff.save(diff_path) im1_path = save_path + "/im1.TIF" im1.save(im1_path) im2_path = save_path + "/im2.TIF" im2.save(im2_path)
def normalize(img, bit_depth=None): """Linear normalization and conversion to grayscale of an image.""" img = ImageOps.grayscale(img) img = ImageOps.autocontrast(img) if bit_depth is not None: img = ImageOps.posterize(img, bit_depth) return img
def contrast(self): # todo: autocontrast, except if there is an argument, then adjust contrast """Apply autocontrast to the drawing context.""" if self.mode != 'RGB': raise Exception("RGB mode required for 'contrast'") self._render() self._image = ImageOps.autocontrast(self._image) self._ctx = None
def filter_contrastToAlpha(image, baseDir): alpha = Image.new('L', image.size, 255) alpha.paste(image, mask=get_alpha(image)) alpha = ImageOps.invert(alpha) alpha = ImageOps.autocontrast(alpha) return Image.merge('LA', [Image.new('L', image.size), alpha])
def convert(action,image_name): # # actions = Actions() # image_path = gray(image_name) # # return image_path # return (render_template('core/convert.html', path=image_path, name=image_name)) # return action if not image_name: return (redirect('/')) else: if action == "gray": img = Image.open(UPLOAD_FOLDER + '/' + image_name).convert('L') elif action == "invert": img = Image.open(UPLOAD_FOLDER + '/' + image_name) img = ImageChops.invert(img) elif action == "sharpen": img = Image.open(UPLOAD_FOLDER + '/' + image_name).filter(ImageFilter.UnsharpMask(radius=2, percent=150, threshold=3)) elif action == "contrast": img = Image.open(UPLOAD_FOLDER + '/' + image_name) img = ImageOps.autocontrast(img, cutoff=5, ignore=None) elif action == "equalize": img = Image.open(UPLOAD_FOLDER + '/' + image_name) img = ImageOps.equalize(img, mask=None) elif action == "solarize": img = Image.open(UPLOAD_FOLDER + '/' + image_name) img = ImageOps.solarize(img, threshold=128) url = "/convert/"+action+"/"+image_name filename = str(time.time()) + image_name img.save(SAVE_FOLDER + '/' + filename) image_path = 'results/' + filename return (render_template('core/index.html', path=image_path, name=image_name, url=url))
def preprocess_chip(am, pil_filt): logdbg('prepocessing') # Convert to grayscale # raw_chip = cm.cx2_raw_chip(6) # --- Resize --- # --- Filters --- #if am.algo_prefs.preproc.histeq_bit : ##pil_filt = ImageOps.equalize(pil_filt) #img_rescale = exposure.equalize_hist(np.asarray(pil_filt)) #pil_filt = Image.fromarray(histeq(np.asarray(pil_filt))).convert('L') if am.algo_prefs.preproc.histeq_bit: from hotspotter.algo.imalgos import histeq logdbg('Equalizing Histogram') pil_filt = histeq(pil_filt) if am.algo_prefs.preproc.adapt_histeq_bit: from hotspotter.algo.imalgos import adapt_histeq logdbg('Adaptive Equalizing Histogram') pil_filt = Image.fromarray(adapt_histeq(np.asarray(pil_filt))) if am.algo_prefs.preproc.contrast_stretch_bit: from hotspotter.algo.imalgos import contrast_stretch logdbg('Stretching Histogram') pil_filt = Image.fromarray(contrast_stretch(np.asarray(pil_filt))) if am.algo_prefs.preproc.autocontrast_bit : logdbg('PIL Autocontrast') pil_filt = ImageOps.autocontrast(pil_filt) if am.algo_prefs.preproc.bilateral_filt_bit : logdbg('O(1) Bilateral Filter Approximation') from hotspotter.tpl.other.shiftableBF import shiftableBF pil_filt = Image.fromarray(shiftableBF(np.asarray(pil_filt))) return pil_filt
def hilightEdges(self): """ """ img = self.image.copy() img = ImageOps.equalize(img) xneg = ImageChops.difference(img, img.offset(-1,0)) xpos = ImageChops.difference(img, img.offset(1,0)) yneg = ImageChops.difference(img, img.offset(0,-1)) ypos = ImageChops.difference(img, img.offset(0,1)) xmax = ImageChops.lighter(xneg, xpos) ymax = ImageChops.lighter(yneg, ypos) xymax = ImageChops.lighter(xmax,ymax) xymax.show() xymax = ImageOps.autocontrast(xymax) xymax.show() xymax = ImageOps.posterize(xymax, 3) xymax = ImageOps.equalize(xymax) xymax.show() xymax = ImageOps.posterize(xymax, 2) xymax.show() self.image.show() self.image = ImageChops.screen(self.image, xymax) self.image.show()
def filter_contrastToAlpha(image, baseDir): # In order to generate an alpha channel for images using a palette, we must # convert the image to RGBA. It's important to use RGBA, not LA (grayscale+alpha), # since PIL can't reliably convert P to LA. Also initially, we created an # alpha channel by replacing opaque pixels with a high mark and transparent # pixels with a low mark. However, it turned out that you can't rely on the # value of Image.info['transparency'] since in case the transparency is # specified in bytes (pngout loves to do that), we can't associate that value # with transparent pixels. Moreover, some versions of PIL raise a warning # when such images are pasted into another image. if image.mode == 'P' and 'transparency' in image.info: image = image.convert('RGBA') # Image.paste() ignores the alpha channel of the pasted image, but expects # the mask to be passed as separate argument. So we have to extract the alpha # channel (if any) from the image we are going to paste. if image.mode in ('RGBA', 'LA'): mask = image.split()[image.getbands().index('A')] else: mask = None alpha = Image.new('L', image.size, 255) alpha.paste(image, mask=mask) alpha = ImageOps.invert(alpha) alpha = ImageOps.autocontrast(alpha) return Image.merge('LA', [Image.new('L', image.size), alpha])
def FindRow(dots, tlDotIndex, rowNum): # Find the first quad quadIndices = FindQuad(dots, tlDotIndex) # Keep track of the bottom-left point of the first quad so we can return it later blPoint = None if(len(quadIndices) > 1 and quadIndices[1] != None): blPoint = quadIndices[1] # Start looking for more of 'em colNum = 0 squares = [] while(len(quadIndices) > 3 and quadIndices[0] is not None and quadIndices[1] is not None and quadIndices[2] is not None and quadIndices[3] is not None): # Translate from indices into coordinates quad = [dots[index] for index in quadIndices] # Found a box - crop it out of the original squares.append(ImageOps.autocontrast(imageOriginal.transform(outputSize, Image.QUAD, (quad[0][0], quad[0][1], quad[1][0], quad[1][1], quad[2][0], quad[2][1], quad[3][0], quad[3][1]), Image.BICUBIC), 2)) colNum = colNum + 1 # See if we're drawing an output grid for debugging if(drawDebuggingGrid): for p in range(0, 3): drawDebuggingGrid.line([(quad[p][0], quad[p][1]), (quad[p + 1][0], quad[p + 1][1])], fill=(0, 64 + (p * 48), 0), width=3) drawDebuggingGrid.line([(quad[3][0], quad[3][1]), (quad[0][0], quad[0][1])], fill=(0, 255, 0), width=3) # Continue on to the next quad in the line quadIndices = FindQuad(dots, quadIndices[3]) # Return both the first point's bottom-left corner and the squares we found return (blPoint, squares)
def apply_polaroid(pixbuf,imageText): width,height = pixbuf.get_width(),pixbuf.get_height() frameSize = (300,320) imageOutputSize = (270,245) imgModified = Image.open('images/frame.jpg') #cropped image to the requested framesize imgModified = ImageOps.fit(imgModified, frameSize, Image.ANTIALIAS, 0, (0.5,0.5)) y = Image.frombytes(K.ImageConstants.RGB_SHORT_NAME,(width,height),pixbuf.get_pixels()) #cropped image to the requested size y = ImageOps.fit(y, imageOutputSize, Image.ANTIALIAS, 0, (0.5,0.5)) y = ImageOps.autocontrast(y, cutoff=2) y = ImageEnhance.Sharpness(y).enhance(2.0) boxOnImage = (12,18) imgModified.paste(y, boxOnImage) #text on image textWidget = ImageDraw.Draw(imgModified).textsize(imageText) fontxy = (frameSize[0]/2 - textWidget[0]/2, 278) ImageDraw.Draw(imgModified).text(fontxy, imageText,fill=(40,40,40)) imgOutput = Image.new(imgModified.mode, (300,320)) imgOutput.paste(imgModified, (imgOutput.size[0]/2-imgModified.size[0]/2, imgOutput.size[1]/2-imgModified.size[1]/2)) return I.fromImageToPixbuf(imgOutput)
def hideImage(self, srcPath, targetPath, outputPath, s=4): try: im_src = open(srcPath, 'rb') except IOError: print 'can not open the %s' % srcPath exit(0) try: im_dest = open(outputPath, 'wb') except IOError: print 'can not open the %s' % outputPath exit(0) im_dest.write(im_src.read()) im_dest.close() im_src.close() try: src = Image.open(outputPath) except IOError: print 'can not open the %s' % srcPath exit(0) key = ImageOps.autocontrast(Image.open(targetPath).resize(src.size)) for x in range(src.size[0]): for y in range(src.size[1]): p = src.getpixel((x,y)) q = key.getpixel((x,y)) r = p[0] - (p[0] % s) + (s * q[0] / 255) g = p[1] - (p[1] % s) + (s * q[1] / 255) b = p[2] - (p[2] % s) + (s * q[2] / 255) src.putpixel((x,y), (r, g, b)) src.save(outputPath)
def process(self): self.image = self.image.convert('RGB') self.image = ImageOps.autocontrast(self.image) if not self.options.forcecolor: self.image = self.image.convert('L') self.image.thumbnail(self.options.profileData[1], Image.LANCZOS) self.save()
def detect_objects(fn, image): """Detects faces and then crops the image.""" #grayscale = cvCreateImage(cvSize(image.width, image.height), 8, 1) #cvCvtColor(image, grayscale, CV_BGR2GRAY) storage = cvCreateMemStorage(0) cvClearMemStorage(storage) #cvEqualizeHist(grayscale, grayscale) cascade = cvLoadHaarClassifierCascade(CLASSIFIER, cvSize(1,1)) faces = cvHaarDetectObjects(image, cascade, storage, 1.3, 3, CV_HAAR_DO_CANNY_PRUNING, cvSize(20,20)) if faces: i = 1 for f in faces: #newfn = fn + ".output.jpg" #os.system("convert %s -stroke red -fill none -draw 'rectangle %d,%d %d,%d' %s" % (fn, f.x, f.y, f.x+f.width, f.y+f.height, newfn)) #os.system("mv %s %s.orig" % (fn, fn)) #os.system("mv %s %s" % (newfn, fn)) #print("[(%d,%d) -> (%d,%d)]" % (f.x, f.y, f.x+f.width, f.y+f.height)) file, ext = os.path.splitext(fn) im = Image.open(fn) # Increase selected area by 50px on each side then crop im = im.crop((f.x-50, f.y-50, f.x+f.width+50, f.y+f.height+50)) # Minor contrast adjustment im = ImageOps.autocontrast(im, cutoff=0.5) im.load() crop = '%s/%s_crop_%s.jpg' % (CROP_DIR, os.path.basename(file), i) im.save(crop, "JPEG") check_crop(crop) i += 1
def apply_autocontrast(pixbuf,cutoff): ''' autoconstrast removes cutoff % of lightest and darkest pixels and then remaps the image so the darkest pixel becomes black and the lightest white ''' width,height = pixbuf.get_width(),pixbuf.get_height() y = ImageOps.autocontrast(Image.frombytes(K.ImageConstants.RGB_SHORT_NAME,(width,height),pixbuf.get_pixels() ) ,cutoff) return I.fromImageToPixbuf(y)
def do_sepia(img): sepia = make_linear_ramp((255, 240, 192)) if img.mode != "L": img = img.convert("L") img = ImageOps.autocontrast(img) img.putpalette(sepia) img = img.convert("RGB") return img
def sepia(im): sepia = make_linear_ramp((255, 240, 192)) if im.mode != "L": im = im.convert("L") # optional: apply contrast enhancement here, e.g. im = ImageOps.autocontrast(im) # apply sepia palette im.putpalette(sepia) return im
def process_image(i, bgconf): FILTERS = ( "BLUR", "CONTOUR", "DETAIL", "EDGE_ENHANCE", "EDGE_ENHANCE_MORE", "EMBOSS", "FIND_EDGES", "SMOOTH", "SMOOTH_MORE", "SHARPEN", ) TRANSPOSITIONS = ("FLIP_LEFT_RIGHT", "FLIP_TOP_BOTTOM", "ROTATE_90", "ROTATE_180", "ROTATE_270") CONTRAST_METHODS = ("enhance",) OPS = ("autocontrast", "putpalette") def linear_ramp(r, g, b): ramp = [] for i in range(255): ramp.extend((int(r * i / 255), int(g * i / 255), int(b * i / 255))) return ramp RAMP_FUNCTIONS = {"linear": linear_ramp} ramps = {} for name, data in bgconf.get("ramps", {}).items(): method = RAMP_FUNCTIONS[data.pop("function")] ramps[name] = method(**data) for operation in bgconf.get("operations", []): method = None for key, value in operation.items(): method = key arg = value break if method == "transpose" and arg in TRANSPOSITIONS: i = i.transpose(getattr(Image, arg)) elif method == "convert" and arg in ("L", "RGB"): i = i.convert(arg) elif method == "autocontrast": i = ImageOps.autocontrast(i) elif method == "putpalette": i.putpalette(ramps[arg]) elif method == "filter" and arg in FILTERS: i.filter(getattr(ImageFilter, arg)) elif method == "point_multiply": i = i.point(lambda p: p * arg) elif method == "contrast": e = ImageEnhance.Contrast(i) for contrast in arg: for contrast_method, contrast_arg in contrast.items(): break if contrast_method in CONTRAST_METHODS: getattr(e, contrast_method)(contrast_arg) return i
def process(self, image): """ Args: image: The image to process Returns: a single image, or a list containing one or more images """ BaseFilter.process(self, image) if self.mode != 'gray': raise RuntimeError("NormalizeContrast only supports grayscale images.") if self.region == 'bbox': bbox = image.split()[1].getbbox() croppedImage = image.crop(bbox) croppedImage.load() alpha = croppedImage.split()[1] croppedImage = \ ImageOps.autocontrast(croppedImage.split()[0], cutoff=self.cutoff) croppedImage.putalpha(alpha) image.paste(croppedImage, image.bbox) elif self.region == 'mask': bbox = image.split()[1].getbbox() croppedImage = image.crop(bbox) croppedImage.load() alpha = croppedImage.split()[1] # Fill in the part of the cropped image outside the bounding box with a # uniform shade of gray grayImage = ImageChops.constant(croppedImage, 128) compositeImage = Image.composite(croppedImage, grayImage, alpha) # Equalize the composite image compositeImage = ImageOps.autocontrast(compositeImage.split()[0], cutoff=self.cutoff) # Paste the part of the equalized image within the mask back # into the cropped image croppedImage = Image.composite(compositeImage, croppedImage, alpha) croppedImage.putalpha(alpha) # Paste the cropped image back into the full image image.paste(croppedImage, bbox) elif self.region == 'all': alpha = image.split()[1] image = ImageOps.autocontrast(image.split()[0], cutoff=self.cutoff) image.putalpha(alpha) return image
def GetImage(self): imgs = [] averages = 1 for i in range(averages): time.sleep(0.01) imgs.append(self.cam.getImage()) while len(imgs) > 1: imgs = self.average(imgs) return ImageOps.autocontrast(imgs[0], 0.0)
def Draw(self, dc): ## Gets the image from the camera and feeds it into the dc dc.Clear() source = self.cam.getImage() source = source.resize((self.Width, self.Height), Image.NEAREST) source = ImageOps.autocontrast(source,0.0) self.image = wx.EmptyImage(source.size[0],source.size[1]) self.image.SetData(source.convert("RGB").tostring()) bitmap = self.image.ConvertToBitmap() dc.DrawBitmap(bitmap,0,0)
def auto_contrast(img, **__): return ImageOps.autocontrast(img)
def __init__(self, p1, operation1, magnitude_idx1, p2, operation2, magnitude_idx2): ranges = { "shearX": np.linspace(-0.3, 0.3, 10), "shearY": np.linspace(-0.3, 0.3, 10), "translateX": np.linspace(-150 / 331, 150 / 331, 10), "translateY": np.linspace(-150 / 331, 150 / 331, 10), "rotate": np.linspace(-30, 30, 10), "color": np.linspace(0.1, 1.9, 10), "posterize": np.round(np.linspace(4, 8, 10), 0).astype(np.int), "solarize": np.linspace(0, 256, 10), "contrast": np.linspace(0.1, 1.9, 10), "sharpness": np.linspace(0.1, 1.9, 10), "brightness": np.linspace(0.1, 1.9, 10), "autocontrast": [0] * 10, "equalize": [0] * 10, "invert": [0] * 10 } func = { "shearX": lambda img, magnitude: shear(img, magnitude * 180, direction="x"), "shearY": lambda img, magnitude: shear(img, magnitude * 180, direction="y"), "translateX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, magnitude * img.size[0], 0, 1, 0), fillcolor=(128, 128, 128)), "translateY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, 0, 1, magnitude * img.size[1]), fillcolor=(128, 128, 128)), "rotate": lambda img, magnitude: img.rotate(magnitude), "color": lambda img, magnitude: ImageEnhance.Color(img).enhance(magnitude), "posterize": lambda img, magnitude: ImageOps.posterize(img, magnitude), "solarize": lambda img, magnitude: ImageOps.solarize(img, magnitude), "contrast": lambda img, magnitude: ImageEnhance.Contrast(img).enhance(magnitude ), "sharpness": lambda img, magnitude: ImageEnhance.Sharpness(img).enhance( magnitude), "brightness": lambda img, magnitude: ImageEnhance.Brightness(img).enhance( magnitude), "autocontrast": lambda img, magnitude: ImageOps.autocontrast(img), "equalize": lambda img, magnitude: ImageOps.equalize(img), "invert": lambda img, magnitude: ImageOps.invert(img) } # self.name = "{}_{:.2f}_and_{}_{:.2f}".format( # operation1, ranges[operation1][magnitude_idx1], # operation2, ranges[operation2][magnitude_idx2]) self.p1 = p1 self.operation1 = func[operation1] self.magnitude1 = ranges[operation1][magnitude_idx1] self.p2 = p2 self.operation2 = func[operation2] self.magnitude2 = ranges[operation2][magnitude_idx2]
def __init__(self, num_layers=2, magnitude=5, fillcolor=(128, 128, 128)): self.num_layers = num_layers self.magnitude = magnitude self.max_level = 10 abso_level = self.magnitude / self.max_level self.level_map = { "shearX": 0.3 * abso_level, "shearY": 0.3 * abso_level, "translateX": 150.0 / 331 * abso_level, "translateY": 150.0 / 331 * abso_level, "rotate": 30 * abso_level, "color": 0.9 * abso_level, "posterize": int(4.0 * abso_level), "solarize": 256.0 * abso_level, "contrast": 0.9 * abso_level, "sharpness": 0.9 * abso_level, "brightness": 0.9 * abso_level, "autocontrast": 0, "equalize": 0, "invert": 0 } # from https://stackoverflow.com/questions/5252170/ # specify-image-filling-color-when-rotating-in-python-with-pil-and-setting-expand def rotate_with_fill(img, magnitude): rot = img.convert("RGBA").rotate(magnitude) return Image.composite(rot, Image.new("RGBA", rot.size, (128, ) * 4), rot).convert(img.mode) rnd_ch_op = random.choice self.func = { "shearX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, magnitude * rnd_ch_op([-1, 1]), 0, 0, 1, 0), Image.BICUBIC, fillcolor=fillcolor), "shearY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, magnitude * rnd_ch_op([-1, 1]), 1, 0), Image.BICUBIC, fillcolor=fillcolor), "translateX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, magnitude * img.size[0] * rnd_ch_op([-1, 1]), 0, 1, 0), fillcolor=fillcolor), "translateY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, 0, 1, magnitude * img.size[1] * rnd_ch_op([-1, 1])), fillcolor=fillcolor), "rotate": lambda img, magnitude: rotate_with_fill(img, magnitude), "color": lambda img, magnitude: ImageEnhance.Color(img).enhance( 1 + magnitude * rnd_ch_op([-1, 1])), "posterize": lambda img, magnitude: ImageOps.posterize(img, magnitude), "solarize": lambda img, magnitude: ImageOps.solarize(img, magnitude), "contrast": lambda img, magnitude: ImageEnhance.Contrast(img).enhance( 1 + magnitude * rnd_ch_op([-1, 1])), "sharpness": lambda img, magnitude: ImageEnhance.Sharpness(img).enhance( 1 + magnitude * rnd_ch_op([-1, 1])), "brightness": lambda img, magnitude: ImageEnhance.Brightness(img).enhance( 1 + magnitude * rnd_ch_op([-1, 1])), "autocontrast": lambda img, magnitude: ImageOps.autocontrast(img), "equalize": lambda img, magnitude: ImageOps.equalize(img), "invert": lambda img, magnitude: ImageOps.invert(img) }
def forward(self, data, state): im = Image.fromarray(data) im = ImageOps.autocontrast(im) return np.copy(np.asarray(im))
def auto_contrast(img): return ImageOps.autocontrast(img) return F.autocontrast(img)
im = self.xform(im, level) return im name = self.name + '({:.1f},{})'.format(probability, level) return TransformFunction(return_function, name) ################## Transform Functions ################## identity = TransformT('identity', lambda pil_img, level: pil_img) flip_lr = TransformT( 'FlipLR', lambda pil_img, level: pil_img.transpose(Image.FLIP_LEFT_RIGHT)) flip_ud = TransformT( 'FlipUD', lambda pil_img, level: pil_img.transpose(Image.FLIP_TOP_BOTTOM)) # pylint:disable=g-long-lambda auto_contrast = TransformT( 'AutoContrast', lambda pil_img, level: ImageOps.autocontrast(pil_img)) equalize = TransformT('Equalize', lambda pil_img, level: ImageOps.equalize(pil_img)) invert = TransformT('Invert', lambda pil_img, level: ImageOps.invert(pil_img)) # pylint:enable=g-long-lambda blur = TransformT('Blur', lambda pil_img, level: pil_img.filter(ImageFilter.BLUR)) smooth = TransformT('Smooth', lambda pil_img, level: pil_img.filter(ImageFilter.SMOOTH)) def _rotate_impl(pil_img, level): """Rotates `pil_img` from -30 to 30 degrees depending on `level`.""" degrees = int_parameter(level, min_max_vals.rotate.max) if random.random() > 0.5: degrees = -degrees
print 'Image Size: %d x %d' % (d[0], d[1]) dtype = get_numpy_array_type(pf) gdcm_array = image.GetBuffer() result = numpy.frombuffer(gdcm_array, dtype=dtype) maxV = float(result[result.argmax()]) ## linear gamma adjust #result = result + .5*(maxV-result) ## log gamma result = numpy.log(result+50) ## 50 is apprx background level maxV = float(result[result.argmax()]) result = result*(2.**8/maxV) ## histogram stretch result.shape = d return result if __name__ == "__main__": import sys r = gdcm.ImageReader() filename = sys.argv[1] r.SetFileName( filename ) if not r.Read(): sys.exit(1) numpy_array = gdcm_to_numpy( r.GetImage() ) ## L is 8 bit grey ## http://www.pythonware.com/library/pil/handbook/concepts.htm pilImage = Image.frombuffer('L', numpy_array.shape, numpy_array.astype(numpy.uint8), 'raw','L',0,1) ## cutoff removes background noise and spikes pilImage = ImageOps.autocontrast(pilImage, cutoff=.1) pilImage.save(sys.argv[1]+'.jpg')
def auto_contrast(img, magnitude): img = ImageOps.autocontrast(img) return img
f = self.pil_transformer(PARAMETER_MAX, lever) return pil_unwrap(f(pil_wrap(image))) ################## Transform Functions ################## identity = TransformT('identity', lambda pil_img, level: pil_img) flip_lr = TransformT( 'FlipLR', lambda pil_img, level: pil_img.transpose(Image.FLIP_LEFT_RIGHT)) flip_ud = TransformT( 'FlipUD', lambda pil_img, level: pil_img.transpose(Image.FLIP_TOP_BOTTOM)) # pylint:disable=g-long-lambda # Maximize the the image contrast, by making the darkest pixel black and lightest pixel white. auto_contrast = TransformT( 'AutoContrast', lambda pil_img, level: ImageOps.autocontrast( pil_img.convert('RGB')).convert('RGBA')) # Equalize the image histogram. equalize = TransformT( 'Equalize', lambda pil_img, level: ImageOps.equalize(pil_img.convert('RGB') ).convert('RGBA')) # Invert the pixels of the image. invert = TransformT( 'Invert', lambda pil_img, level: ImageOps.invert(pil_img.convert('RGB')). convert('RGBA')) # pylint:enable=g-long-lambda blur = TransformT('Blur', lambda pil_img, level: pil_img.filter(ImageFilter.BLUR))
def __call__(self, x): return ImageOps.autocontrast(x)
def create_color_image(img, palette_tuple): sepia = img.copy().convert("L") sepia = ImageOps.autocontrast(sepia) sepia.putpalette(make_linear_ramp(palette_tuple)) return sepia.convert("RGB")
# (C) Copyright 2020 Pavel Tisnovsky # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Pavel Tisnovsky # from PIL import Image from PIL import ImageOps filename = "Lenna.png" try: test_image = Image.open(filename) test_image.load() modified_image_1 = ImageOps.autocontrast(test_image, cutoff=0) modified_image_2 = ImageOps.autocontrast(test_image, cutoff=50) modified_image_3 = ImageOps.autocontrast(test_image, cutoff=75) test_image.show() modified_image_1.show() modified_image_2.show() modified_image_3.show() except Exception as e: print(e)
def process_image(image_1, image_2): if image_1 <> 'none': # NS or SN pass? evening_pass = False pass_time = int(image_1[-4:]) if ((pass_time > 1600) or (pass_time < 0400)): evening_pass = True # first check which channels were active active_channels = [0, 0, 0, 0, 0, 0] active_decoded_channels = detect_blanks(image_1) if active_decoded_channels == 'none': return [], [0, 0, 0, 0, 0, 0] # no image was decoded from recording active_channels[0] = active_decoded_channels[0] active_channels[1] = active_decoded_channels[1] active_channels[4] = active_decoded_channels[2] active_decoded_channels = detect_blanks(image_2) active_channels[2] = active_decoded_channels[0] active_channels[3] = active_decoded_channels[1] active_channels[5] = active_decoded_channels[2] logging.debug('Detected active channels: ' + str(active_channels)) if (sum(active_channels) <> 3): logging.debug('Amount of active channels incorrect (%.0f)' % active_channels) image_1_dir = os.path.join(main_folder, 'Data', image_1 + '.bmp') image_2_dir = os.path.join(main_folder, 'Data', image_2 + '.bmp') logging.debug('processing file %s' % image_1_dir) channels = [0] * 6 image_125 = Image.open(image_1_dir) ch_4, ch_1, ch_0 = image_125.split() image_346 = Image.open(image_2_dir) ch_5, ch_3, ch_2 = image_346.split() list_of_images = [] if (active_channels[:2] == [1, 1]): image_dir = os.path.join(main_folder, 'Images', image_1 + '_122.jpg') image = Image.merge("RGB", (ch_1, ch_1, ch_0)) image.save(image_dir, quality=90, subsampling=0) list_of_images.append(image_dir) if (active_channels == [1, 1, 1, 0, 0, 0]): image_dir = os.path.join(main_folder, 'Images', image_1 + '_123.jpg') image = Image.merge("RGB", (ch_2, ch_1, ch_0)) image.save(image_dir, quality=90, subsampling=0) list_of_images.append(image_dir) if (active_channels == [1, 1, 0, 1, 0, 0]): image_dir = os.path.join(main_folder, 'Images', image_1 + '_124.jpg') image = Image.merge("RGB", (ch_3, ch_1, ch_0)) image.save(image_dir, quality=90, subsampling=0) list_of_images.append(image_dir) if (active_channels[4] == 1): image_dir = os.path.join(main_folder, 'Images', image_1 + '_555.jpg') image = Image.merge("RGB", (ch_4, ch_4, ch_4)) image = ImageOps.invert(image) image = ImageOps.autocontrast(image) #thermal information gets lost here, but we get better looking images image.save(image_dir, quality=90, subsampling=0) list_of_images.append(image_dir) if (active_channels[5] == 1): image_dir = os.path.join(main_folder, 'Images', image_1 + '_666.jpg') image = Image.merge("RGB", (ch_5, ch_5, ch_5)) image = ImageOps.invert(image) image = ImageOps.autocontrast(image) #thermal information gets lost here, but we get better looking images image.save(image_dir, quality=90, subsampling=0) list_of_images.append(image_dir) for image_dir in list_of_images: if (evening_pass): image = Image.open(image_dir) image = image.rotate(180) image.save(image_dir) logging.debug('Saved %s' % image_dir) return list_of_images, active_channels else: return [], [0, 0, 0, 0, 0, 0]
mynames7 = np.sort(rmynames7) mynames8 = np.sort(rmynames8) #print(mynames1[0,0]) mynames = np.hstack((np.ravel(mynames1[0,:]), "next", np.ravel(mynames2[0,:]), "next", np.ravel(mynames3[0,:]), "next", np.ravel(mynames4[0,:]), "next", np.ravel(mynames5[0,:]), "next", np.ravel(mynames6[0,:]), "next", np.ravel(mynames7[0,:]), "next", np.ravel(mynames8[0,:]), "end")) i = 0 j = 0 with open('rem10train_l_100_60.csv', 'wb') as csvfile: mywriter = csv.writer(csvfile, delimiter=',') while mynames[i] != "end": if mynames[i] != "next": print("Progress: " + str((float(i)/float(len(mynames)))*100.0) + "%, " + str(mynames[i])) im = Image.open(mynames[i]) im = im.convert('L') #1 = B&W, L = grey im = ImageOps.autocontrast(im, cutoff=10, ignore=None) #print(im.size) im = im.resize((120,80),Image.ANTIALIAS) #300,160, 150, 80 im = ImageOps.crop(im, border=10) #im.show() #exit() #''' mycsv = np.hstack((str(mynames[i]),str(j),np.ravel(np.array(im.getdata())).astype('str'))) mywriter.writerow(mycsv) del(mycsv) #''' ''' no_of_dup = 10 for k in range(0,no_of_dup): mycsv = np.hstack((str('rot' + str(k) + '-' + mynames[i]),str(j),np.ravel(np.array(im.getdata())).astype('str'))) mywriter.writerow(mycsv)
def image_autocontrast(image, name, save_path): image = ImageOps.autocontrast(image, 15) image.save(save_path + "/" + name)
box[3] + int(left_right_dist / 2) ] region = im.crop(sq_box) region_pix = np.asarray(region) # To make a 20x20 sized image with the same ratio size = [20, 20] region.thumbnail(size, Image.ANTIALIAS) new_size = [28, 28] new_img = Image.new("L", new_size, color=225) new_img.paste(region, (int( (new_size[0] - size[0]) / 2), int((new_size[1] - size[1]) / 2))) new_img.show() new_img = ImageOps.autocontrast(new_img) new_img.show() pix = new_img.load() pixels = [] for i in range(0, 28): for j in range(0, 28): pixels.append(abs(pix[j, i] - 255) / 265) max_pixel = max(pixels) for p in range(0, len(pixels)): pixels[p] = pixels[p] / max_pixel for i in range(0, 28): print("") for j in range(28): if pixels[i * 28 + j] < 0.3: print("-", end="")
def _load_img_as_tensor(file_name, r1, r2, r3, noiseLevel=0): output_size = 224 with Image.open(file_name) as img: #minV, maxV = img.getextrema() #print (minV, maxV, file_name) #normalize = T.Normalize(mean=[minV,],std=[(maxV-minV/255),]) angle = r1 * 90 img = T.functional.rotate(img, angle) if r2==1: img = T.functional.hflip(img) if r3==1: img = T.functional.vflip(img) # remove noise (all intensity lower than 10) if noiseLevel>0: img = ImageChops.subtract(img, ImageChops.constant(img, noiseLevel)) # Contrast stretching img = ImageOps.autocontrast(img, cutoff=1, ignore=None) #i = np.random.uniform(0,199) #j = np.random.uniform(0,199) #img = T.functional.crop(img, i, j, 312, 312) #img = T.functional.resize(img,output_size) #transform = T.Compose([T.ToTensor(), normalize]) #transform = T.Compose([T.RandomVerticalFlip(), T.RandomHorizontalFlip(), T.ToTensor(), normalize]) transform = T.ToTensor() return transform(img)
differentBands = '' #To be appened with bands that have at least one different pixel if raster_difference.getbbox() is None: #The images are identical print('Wavedrom and Wavedrompy rendered to indentical PNG images') else: #Check which individual bands are different, and add bands with differences to `differentBands` for bandName, band in zip(raster_difference.getbands(), raster_difference.split()): if band.getbbox() is not None: differentBands += bandName print('Difference in ' + bandName + ' channel') #Display differences in color bands, ignoring alpha if 'R' in differentBands or 'G' in differentBands or 'B' in differentBands: print('Difference of RGB:') noAlpha = Image.merge('RGB', raster_difference.split()[0:3]) noAlphaEnhanced = ImageOps.autocontrast(noAlpha) display(noAlphaEnhanced) noAlphaEnhanced.save('./tmp/' + test_name + '_noAlphaDiff.png') #Display differences in alpha band as grayscale image if 'A' in differentBands: print('Difference of alpha:') alphaOnly = raster_difference.split()[-1] alphaOnlyEnhanced = ImageOps.autocontrast(alphaOnly) display(alphaOnlyEnhanced) alphaOnlyEnhanced.save('./tmp/' + test_name + '_alphaOnlyDiff.png') #%% Compose the original and difference images import cairosvg, io noAlphaCopy = noAlphaEnhanced.copy()
def add_augment(img, policy): shape = img.shape #shape[0]:height, shape[1]: width, shape[2]: channel if shape[2] == 3: fcol = np.mean(img, axis=(0, 1)).astype('uint8') fcol_int = np.mean(img).astype('uint8') fmod = 'RGB' fsha = (shape[1], shape[0], 3) for p in policy: if p['op'] == 'non': pass # flip(mirror) elif p['op'] == 'mrx': img = np.fliplr(img) elif p['op'] == 'mry': img = np.flipud(img) elif p['op'] == '180': img = np.fliplr(np.flipud(img)) #crop elif p['op'] == 'crp': img = Image.fromarray(img) mag = p['mag'] / 10.0 * np.random.uniform(0.0, 1.0) zoom = np.random.uniform(0.25 + 0.75 * (1 - mag) - 1e-6, 1 + 1e-6) left = np.random.uniform( 0, shape[1] * np.random.uniform(1e-6, 1 - zoom + 1e-4)) #left upper = np.random.uniform( 0, shape[0] * np.random.uniform(1e-6, 1 - zoom + 1e-4)) #upper right = left + zoom * shape[1] #right lower = upper + zoom * shape[0] #lower img = img.crop((left, upper, right, lower)) img = img.resize((shape[1], shape[0]), resample=Image.BICUBIC) #cutout elif p['op'] == 'ct1': rand = np.random.uniform(0, 1, 2) blob = (np.array( [rand[1] * shape[1], rand[1] * (0.5 + rand[0]) * shape[0]]) * p['mag'] / 20.).astype('int') if blob[1] * blob[0] != 0: pxls = (np.random.randint(shape[1] - blob[0] - 1), np.random.randint(shape[0] - blob[1] - 1)) if shape[2] == 3: blob = np.append(blob, [3]) noise = Image.fromarray( np.clip(np.random.randint(255, size=blob), 0, 255).astype('uint8')) img = Image.fromarray(img) img.paste(noise, pxls) #img = np.asarray(img) elif p['op'] == 'ct2': img = Image.fromarray(img) rand = np.random.uniform(0, 1, 2) blob = (np.array( [rand[1] * shape[1], rand[1] * (0.5 + rand[0]) * shape[0]]) * p['mag'] / 20.).astype('int') if blob[1] * blob[0] != 0: pxls = (np.random.randint(shape[1] - blob[0] - 1), np.random.randint(shape[0] - blob[1] - 1)) if img.mode == 'RGB': blob = np.append(blob, [3]) draw = ImageDraw.Draw(img) draw.rectangle( [pxls[0], pxls[1], pxls[0] + blob[1], pxls[1] + blob[0]], fill=tuple(fcol)) #invert elif p['op'] == 'inv': img = np.invert(img) #rotation elif p['op'] == 'rot': img = Image.fromarray(img) angle = np.random.uniform(-45, 45) * p['mag'] / 10. img = img.rotate(angle, resample=Image.BICUBIC, fillcolor=tuple(fcol)) #sharpness elif p['op'] == 'sha': img = Image.fromarray(img) enha = 1 + np.random.uniform(-1, 1) * p['mag'] / 10. img = ImageEnhance.Sharpness(img).enhance(enha) #shear elif p['op'] == 'srx': img = Image.fromarray(img) shear = np.random.uniform(-0.5, 0.5) * p['mag'] / 10. img = img.transform((shape[1], shape[0]), Image.AFFINE, (1, shear, 0, 0, 1, 0), resample=Image.BICUBIC, fillcolor=tuple(fcol)) elif p['op'] == 'sry': img = Image.fromarray(img) shear = np.random.uniform(-0.5, 0.5) * p['mag'] / 10. img = img.transform((shape[1], shape[0]), Image.AFFINE, (1, 0, 0, shear, 1, 0), resample=Image.BICUBIC, fillcolor=tuple(fcol)) #autocontrast elif p['op'] == 'auc': img = Image.fromarray(img) img = ImageOps.autocontrast(img, cutoff=2) #contrast elif p['op'] == 'con': img = Image.fromarray(img) enha = 1 + np.random.uniform(-1, 1) * p['mag'] / 10. img = ImageEnhance.Contrast(img).enhance(enha) #saturation elif p['op'] == 'clr': img = Image.fromarray(img) enha = 1 + np.random.uniform(-1, 1) * p['mag'] / 10. img = ImageEnhance.Color(img).enhance(enha) #brightness elif p['op'] == 'bri': img = Image.fromarray(img) enha = 1 + np.random.uniform(-1, 1) * p['mag'] / 10. img = ImageEnhance.Brightness(img).enhance(enha) #equalize elif p['op'] == 'eqz': img = Image.fromarray(img) img = ImageOps.equalize(img) #translation elif p['op'] == 'tlx': img = Image.fromarray(img) shift = shape[1] * np.random.uniform(-0.5, 0.5) * p['mag'] / 10. img = img.transform((shape[1], shape[0]), Image.AFFINE, (1, 0, shift, 0, 1, 0), resample=Image.BICUBIC, fillcolor=tuple(fcol)) elif p['op'] == 'tly': img = Image.fromarray(img) shift = shape[0] * np.random.uniform(-0.5, 0.5) * p['mag'] / 10. img = img.transform((shape[1], shape[0]), Image.AFFINE, (1, 0, 0, 0, 1, shift), resample=Image.BICUBIC, fillcolor=tuple(fcol)) #solarize elif p['op'] == 'sol': th = int(256 * (1 - np.random.uniform(0, 1) * p['mag'] / 10.)) img = Image.fromarray(img) if np.random.rand() - 0.5 > 0: img = ImageOps.solarize(img, threshold=th) else: img = ImageOps.invert(img) img = ImageOps.solarize(img, threshold=th) img = ImageOps.invert(img) #posterize elif p['op'] == 'pos': bit = int(8.5 - np.random.uniform(0, 0.5) * p['mag']) img = Image.fromarray(img) img = ImageOps.posterize(img, bit) img = np.asarray(img, dtype=np.uint8) return img
def __init__(self, p1, operation1, magnitude_idx1, p2, operation2, magnitude_idx2, fillcolor=(128, 128, 128)): ranges = { "shearX": np.linspace(0, 0.3, 10), "shearY": np.linspace(0, 0.3, 10), "translateX": np.linspace(0, 150 / 331, 10), "translateY": np.linspace(0, 150 / 331, 10), "rotate": np.linspace(0, 30, 10), "color": np.linspace(0.0, 0.9, 10), "posterize": np.round(np.linspace(8, 4, 10), 0).astype(np.int), "solarize": np.linspace(256, 0, 10), "contrast": np.linspace(0.0, 0.9, 10), "sharpness": np.linspace(0.0, 0.9, 10), "brightness": np.linspace(0.0, 0.9, 10), "autocontrast": [0] * 10, "equalize": [0] * 10, "invert": [0] * 10 } # from https://stackoverflow.com/questions/5252170/specify-image-filling-color-when-rotating-in-python-with-pil-and-setting-expand def rotate_with_fill(img, magnitude): rot = img.convert("RGBA").rotate(magnitude) return Image.composite(rot, Image.new("RGBA", rot.size, (128,) * 4), rot).convert(img.mode) func = { "shearX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, magnitude * random.choice([-1, 1]), 0, 0, 1, 0), Image.BICUBIC, fillcolor=fillcolor), "shearY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, magnitude * random.choice([-1, 1]), 1, 0), Image.BICUBIC, fillcolor=fillcolor), "translateX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, magnitude * img.size[0] * random.choice([-1, 1]), 0, 1, 0), fillcolor=fillcolor), "translateY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, 0, 1, magnitude * img.size[1] * random.choice([-1, 1])), fillcolor=fillcolor), "rotate": lambda img, magnitude: rotate_with_fill(img, magnitude), # "rotate": lambda img, magnitude: img.rotate(magnitude * random.choice([-1, 1])), "color": lambda img, magnitude: ImageEnhance.Color(img).enhance(1 + magnitude * random.choice([-1, 1])), "posterize": lambda img, magnitude: ImageOps.posterize(img, magnitude), "solarize": lambda img, magnitude: ImageOps.solarize(img, magnitude), "contrast": lambda img, magnitude: ImageEnhance.Contrast(img).enhance( 1 + magnitude * random.choice([-1, 1])), "sharpness": lambda img, magnitude: ImageEnhance.Sharpness(img).enhance( 1 + magnitude * random.choice([-1, 1])), "brightness": lambda img, magnitude: ImageEnhance.Brightness(img).enhance( 1 + magnitude * random.choice([-1, 1])), "autocontrast": lambda img, magnitude: ImageOps.autocontrast(img), "equalize": lambda img, magnitude: ImageOps.equalize(img), "invert": lambda img, magnitude: ImageOps.invert(img) } # self.name = "{}_{:.2f}_and_{}_{:.2f}".format( # operation1, ranges[operation1][magnitude_idx1], # operation2, ranges[operation2][magnitude_idx2]) self.p1 = p1 self.operation1 = func[operation1] self.magnitude1 = ranges[operation1][magnitude_idx1] self.p2 = p2 self.operation2 = func[operation2] self.magnitude2 = ranges[operation2][magnitude_idx2]
def imgmsg_to_pil(img_msg, rgba=False): try: if img_msg._type == 'sensor_msgs/CompressedImage': pil_img = Image.open(BytesIO(img_msg.data)) if pil_img.mode.startswith('BGR'): pil_img = pil_bgr2rgb(pil_img) pil_mode = 'RGB' else: pil_mode = 'RGB' if img_msg.encoding in ['mono8', '8UC1']: mode = 'L' elif img_msg.encoding == 'rgb8': mode = 'RGB' elif img_msg.encoding == 'bgr8': mode = 'BGR' elif img_msg.encoding in [ 'bayer_rggb8', 'bayer_bggr8', 'bayer_gbrg8', 'bayer_grbg8' ]: mode = 'L' elif img_msg.encoding in [ 'bayer_rggb16', 'bayer_bggr16', 'bayer_gbrg16', 'bayer_grbg16' ]: pil_mode = 'I;16' if img_msg.is_bigendian: mode = 'I;16B' else: mode = 'I;16L' elif img_msg.encoding == 'mono16' or img_msg.encoding == '16UC1': pil_mode = 'F' if img_msg.is_bigendian: mode = 'F;16B' else: mode = 'F;16' elif img_msg.encoding == '32FC1': pil_mode = 'F' if img_msg.is_bigendian: mode = 'F;32BF' else: mode = 'F;32F' elif img_msg.encoding == 'rgba8': mode = 'BGR' elif img_msg.encoding == 'bgra8': mode = 'RGB' else: raise Exception("Unsupported image format: %s" % img_msg.encoding) pil_img = Image.frombuffer(pil_mode, (img_msg.width, img_msg.height), img_msg.data, 'raw', mode, 0, 1) # 16 bits conversion to 8 bits if pil_mode == 'I;16': pil_img = pil_img.convert('I').point(lambda i: i * (1. / 256.)).convert('L') if pil_img.mode == 'F': pil_img = pil_img.point(lambda i: i * (1. / 256.)).convert('L') pil_img = ImageOps.autocontrast(pil_img) pil_img = ImageOps.invert(pil_img) if rgba and pil_img.mode != 'RGBA': pil_img = pil_img.convert('RGBA') return pil_img except Exception as ex: #print('Can\'t convert image: %s' % ex, file=sys.stderr) print('Cant convert image') return None
def autocontrast(img: Image.Image) -> Image.Image: if not _is_pil_image(img): raise TypeError(f"img should be PIL Image. Got {type(img)}") return ImageOps.autocontrast(img)
def showarray(a, fmt='jpeg'): f = BytesIO() ImageOps.autocontrast(Image.fromarray(a)).save(f, fmt) IPython.display.display(IPython.display.Image(data=f.getvalue()))
def __call__(self, img, ranges): if random.random() < 0.2: img = ImageOps.equalize(img) if random.random() < 0.6: img = ImageOps.autocontrast(img) return img
def _apply_autocontrast(self, data: np.ndarray) -> np.ndarray: im = Image.fromarray(data) im = ImageOps.autocontrast(im) return np.array(im)
def __call__(self, img, ranges): if random.random() < 0.8: img = ImageOps.autocontrast(img) if random.random() < 0.2: img = ImageOps.solarize(img, ranges["solarize"][8]) return img
def autocontrast(pil_img, _): return ImageOps.autocontrast(pil_img)
def create_site(self, sattel_site_id): import voxel_globe.meta.models as models from .tools import PlanetClient import geojson import shutil import voxel_globe.tools.voxel_dir as voxel_dir from datetime import datetime import pytz import json from glob import glob import zipfile import tifffile import numpy as np from PIL import Image, ImageOps import voxel_globe.ingest.models from voxel_globe.tools.camera import save_rpc from vsi.io.image import imread import voxel_globe.ingest.payload.tools as payload_tools site = models.SattelSite.objects.get(id=sattel_site_id) w = site.bbox_min[0] s = site.bbox_min[1] e = site.bbox_max[0] n = site.bbox_max[1] key=env['VIP_PLANET_LABS_API_KEY'] # search dates start = datetime(year=2016, month=1, day=1, tzinfo=pytz.utc) stop = datetime(year=2017, month=1, day=1, tzinfo=pytz.utc) cloudmax=50 platforms = ('planetscope') coords = [[(w,n),(e,n),(e,s),(w,s),(w,n)]] geometry = geojson.Polygon(coords) query = { "start": start, "stop": stop, "aoi": geometry, "cloudmax": cloudmax, "platforms": platforms, } with voxel_dir.storage_dir('external_download') as processing_dir, PlanetClient(key) as client: # count available images # (Planet can return a huge list of images, spanning all images # in their database. Check the count before proceeding) self.update_state(state='QUERYING') nbr = client.countImages(query=query) logger.debug(query) logger.info("Number of images: %d",nbr) scenes = client.describeImages(query=query) #logger.debug(json.dumps(scenes, indent=2)) # thumbs = client.downloadThumbnails(scenes, # folder=processing_dir,type='unrectified', # size='md',format='png') # self.update_state(state='DOWNLOADING', meta={"type":"images", # "total":nbr}) image_set = models.ImageSet(name="Site: %s" % site.name, service_id=self.request.id) image_set.save() camera_set = models.CameraSet(name="Site: %s" % site.name, images=image_set, service_id=self.request.id) camera_set.save() site.image_set = image_set site.camera_set = camera_set site.save() for idx,scene in enumerate(scenes): # update self.update_state(state='DOWNLOADING', meta={"type":"Images", "total":nbr,"index":idx, "site_name": site.name}) # download one scene to ZIP files = client.downloadImages(scene, folder=processing_dir,type='unrectified.zip') filezip = files[0] logger.debug(filezip) # unzip file to isolated folder name,ext = os.path.splitext(os.path.basename(filezip)) logger.debug(name) zip_dir = os.path.join(processing_dir,name) logger.debug(zip_dir) with zipfile.ZipFile(filezip, 'r') as z: z.extractall(zip_dir) os.remove(filezip) logger.debug(glob(os.path.join(zip_dir, '*/'))) dir_name = glob(os.path.join(zip_dir, '*/'))[0] #for dir_name in glob(os.path.join(zip_dir, '*/')): logger.debug(dir_name) rpc_name = glob(os.path.join(dir_name, '*_RPC.TXT'))[0] image_name = glob(os.path.join(dir_name, '*.tif'))[0] #juggle files image_name = payload_tools.move_to_sha256(image_name) rpc_name_new = os.path.join(os.path.dirname(image_name), os.path.basename(rpc_name)) shutil.move(rpc_name, rpc_name_new) rpc_name = rpc_name_new del rpc_name_new scaled_imagename = os.path.join(os.path.dirname(image_name), 'scaled_'+os.path.basename(image_name)) img = imread(image_name) pixel_format = np.sctype2char(img.dtype()) #Make viewable image img2 = img.raster()[:,:,0:3] img2 = img2.astype(np.float32)/np.amax(img2.reshape(-1, 3), axis=0).reshape(1,1,3) #Divide by max for each color img2 = Image.fromarray(np.uint8(img2*255)) #Convert to uint8 for PIL :( img2 = ImageOps.autocontrast(img2, cutoff=1) #autocontrast img2.save(scaled_imagename) del img2 attributes={} if os.path.basename(image_name) == scene['id']+'.tif': attributes['planet_rest_response'] = scene image = models.Image( name="Planet %s" % (os.path.basename(image_name),), image_width=img.shape()[1], image_height=img.shape()[0], number_bands=img.bands(), pixel_format=pixel_format, file_format='zoom', service_id=self.request.id) image.filename_path=image_name image.attributes=attributes image.save() image_set.images.add(image) payload_tools.zoomify_image(scaled_imagename, image.zoomify_path) os.remove(scaled_imagename) rpc = models.RpcCamera(name=os.path.basename(image_name), rpc_path=rpc_name, image=image) rpc.save() camera_set.cameras.add(rpc) return {"site_name" : site.name}
name = self.name + "({:.1f},{})".format(probability, level) return TransformFunction(return_function, name) ################## Transform Functions ################## identity = TransformT("identity", lambda pil_img, level, _: pil_img) flip_lr = TransformT( "FlipLR", lambda pil_img, level, _: pil_img.transpose(Image.FLIP_LEFT_RIGHT)) flip_ud = TransformT( "FlipUD", lambda pil_img, level, _: pil_img.transpose(Image.FLIP_TOP_BOTTOM)) # pylint:disable=g-long-lambda auto_contrast = TransformT( "AutoContrast", lambda pil_img, level, _: ImageOps.autocontrast(pil_img)) equalize = TransformT("Equalize", lambda pil_img, level, _: ImageOps.equalize(pil_img)) invert = TransformT("Invert", lambda pil_img, level, _: ImageOps.invert(pil_img)) # pylint:enable=g-long-lambda blur = TransformT("Blur", lambda pil_img, level, _: pil_img.filter(ImageFilter.BLUR)) smooth = TransformT( "Smooth", lambda pil_img, level, _: pil_img.filter(ImageFilter.SMOOTH)) def _rotate_impl(pil_img, level, _): """Rotates `pil_img` from -30 to 30 degrees depending on `level`.""" degrees = int_parameter(level, 30) if random.random() > 0.5:
else: return msg verify(actual) # Convert the image to png extension = expected.split('.')[-1] if extension != 'png': actual, expected = convert(actual), convert(expected) # open the image files and remove the alpha channel (if it exists) expectedImage = Image.open(expected).convert("RGB") actualImage = Image.open(actual).convert("RGB") # normalize the images expectedImage = ImageOps.autocontrast(expectedImage, 2) actualImage = ImageOps.autocontrast(actualImage, 2) # compare the resulting image histogram functions h1 = expectedImage.histogram() h2 = actualImage.histogram() rms = math.sqrt( reduce(operator.add, map(lambda a, b: (a - b)**2, h1, h2)) / len(h1)) diff_image = os.path.join(os.path.dirname(actual), 'failed-diff-' + os.path.basename(actual)) expected_copy = 'expected-' + os.path.basename(actual) if ((rms / 10000.0) <= tol): if os.path.exists(diff_image): os.unlink(diff_image)