def classify_DCT(image1,image2,size=(32,32),part_size=(8,8)):
	""" 'image1' and 'image2' is a Image Object.
	You can build it by 'Image.open(path)'.
	'Size' is parameter what the image will resize to it and then image will be compared by the pHash.
	It's 32 * 32 when it default. 
	'part_size' is a size of a part of the matrix after Discrete Cosine Transform,which need to next steps.
	It's 8 * 8 when it default. 

	The function will return the hamming code,less is correct. 
	"""
	assert size[0]==size[1],"size error"
	assert part_size[0]==part_size[1],"part_size error"

	image1 = image1.resize(size).convert('L').filter(ImageFilter.BLUR)
	image1 = ImageOps.equalize(image1)
	matrix = get_matrix(image1)
	DCT_matrix = DCT(matrix)
	List = sub_matrix_to_list(DCT_matrix, part_size)
	middle = get_middle(List)
	code1 = get_code(List, middle)


	image2 = image2.resize(size).convert('L').filter(ImageFilter.BLUR)
	image2 = ImageOps.equalize(image2)
	matrix = get_matrix(image2)
	DCT_matrix = DCT(matrix)
	List = sub_matrix_to_list(DCT_matrix, part_size)
	middle = get_middle(List)
	code2 = get_code(List, middle)



	return comp_code(code1, code2)
Ejemplo n.º 2
0
    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 method3(im):
	# equalizes bands individually
	r,g,b,a = im.split()
	r = ImageOps.equalize(r)
	g = ImageOps.equalize(g)
	b = ImageOps.equalize(b)
	im_eq = Image.merge('RGBA', (r,g,b,a))
	im_eq.save("test_m3.png")
Ejemplo n.º 4
0
def test_sanity():

    ImageOps.autocontrast(lena("L"))
    ImageOps.autocontrast(lena("RGB"))

    ImageOps.autocontrast(lena("L"), cutoff=10)
    ImageOps.autocontrast(lena("L"), ignore=[0, 255])

    ImageOps.colorize(lena("L"), (0, 0, 0), (255, 255, 255))
    ImageOps.colorize(lena("L"), "black", "white")

    ImageOps.crop(lena("L"), 1)
    ImageOps.crop(lena("RGB"), 1)

    ImageOps.deform(lena("L"), deformer)
    ImageOps.deform(lena("RGB"), deformer)

    ImageOps.equalize(lena("L"))
    ImageOps.equalize(lena("RGB"))

    ImageOps.expand(lena("L"), 1)
    ImageOps.expand(lena("RGB"), 1)
    ImageOps.expand(lena("L"), 2, "blue")
    ImageOps.expand(lena("RGB"), 2, "blue")

    ImageOps.fit(lena("L"), (128, 128))
    ImageOps.fit(lena("RGB"), (128, 128))
    ImageOps.fit(lena("RGB").resize((1, 1)), (35, 35))

    ImageOps.flip(lena("L"))
    ImageOps.flip(lena("RGB"))

    ImageOps.grayscale(lena("L"))
    ImageOps.grayscale(lena("RGB"))

    ImageOps.invert(lena("L"))
    ImageOps.invert(lena("RGB"))

    ImageOps.mirror(lena("L"))
    ImageOps.mirror(lena("RGB"))

    ImageOps.posterize(lena("L"), 4)
    ImageOps.posterize(lena("RGB"), 4)

    ImageOps.solarize(lena("L"))
    ImageOps.solarize(lena("RGB"))

    success()
Ejemplo n.º 5
0
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))
Ejemplo n.º 6
0
    def run(self):
        while True:
            try:
                camera = WebCamera.objects.get(pk = self._camera.id)
                if camera.motion_control:
                    now = datetime.now()
                    request = get_pool().request("GET", "%s?action=snapshot" % camera.internal_url)
                    try:
                        source = Image.open(BytesIO(request.data))
                        img = ImageOps.equalize(ImageOps.grayscale(source))
                        if self._previous is not None:
                            out = ImageMath.eval("convert(a - b, 'L')", a = img, b = self._previous)
                            out = out.filter(MedianFilter())
                            total = 0
                            for idx, val in enumerate(out.histogram()):
                                total += val * idx
                            if total > 3000000:
                                camera.last_motion = now
                                camera.save()

                                filename = os.path.join(camera.motion_folder, "{:%Y%m%d-%H%M%S}.jpg".format(now))
                                source.save(filename)
                                filesize = os.path.getsize(filename)
                                if filesize < 6700:
                                    os.remove(filename) 

                        self._previous = img
                    finally:
                        request.close()
                else:
                    self._previous = None
            except:
                print("Ignore Exception")
            sleep(1)
Ejemplo n.º 7
0
def pil_to_ascii(img,
                 scalefactor=0.2,
                 invert=False,
                 equalize=True,
                 lut='simple',
                 aspect_correction_factor=None
                 ):
    """
    Generates an ascii string from a PIL image.

    Parameters
    ----------
    img : PIL.Image
        PIL image to transform.
    scalefactor : float
        ASCII characters per pixel.
    invert : bool
        Invert luminance?
    equalize : bool
        equalize histogram (for best results do this).
    lut : str
        Name of the lookup table to use. Currently supports 'simple' and
        'binary'.

    Returns
    -------
    str

    Examples
    --------

    >>> from asciisciit.misc import open_pil_img
    >>> img = open_pil_img("http://i.imgur.com/l2FU2J0.jpg")
    >>> text_img = pil_to_ascii(img, scalefactor=0.3)
    >>> print(text_img)

    >>> from PIL import Image
    >>> img = Image.open("some_image.png")
    >>> text_img = pil_to_ascii(img)
    >>> print(text_img)

    """
    lookup = get_lut(lut)
    if aspect_correction_factor is None:
        aspect_correction_factor = get_aspect_correction_factor(lookup.exemplar)

    img = img.resize(
        (int(img.size[0]*scalefactor), 
         int(img.size[1]*scalefactor*aspect_correction_factor)),
        Image.BILINEAR)
    img = img.convert("L")  # convert to mono
    if equalize:
        img = ImageOps.equalize(img)

    if invert:
        img = ImageOps.invert(img)

    img = np.array(img, dtype=np.uint8)

    return u"\n" + u"".join(lookup.apply(img).flatten().tolist())
Ejemplo n.º 8
0
def apply_equalizer(pixbuf):    
    '''
    creates a uniform distribution of grayscale values in the output image
    '''
    width,height = pixbuf.get_width(),pixbuf.get_height() 
    y = ImageOps.equalize(Image.frombytes(K.ImageConstants.RGB_SHORT_NAME,(width,height),pixbuf.get_pixels() ))
    return I.fromImageToPixbuf(y)
Ejemplo n.º 9
0
def main():
    parser = ArgumentParser()
    parser.add_argument("inage", metavar='INPUT', type=str)
    parser.add_argument("outage", metavar='OUTPUT', type=str)
    parser.add_argument("-p", "--palette", type=str, default="AUTO")
    parser.add_argument("-d", "--dither", type=str, default="BAYER")
    parser.add_argument("-iw", "--width", type=int, default=-1)
    parser.add_argument("-ih", "--height", type=int, default=-1)
    parser.add_argument("-m", "--matrix", type=int, default=-2)
    parser.add_argument("-e", "--equalize", action="store_true", default=False)
    args = parser.parse_args()

    image = Image.open(args.inage)

    if args.equalize:
        image = ImageOps.equalize(image)

    # Create target palette
    if args.palette.upper() == "GB":
        out_palette = gl_c.GAMENIPPER
    elif args.palette.upper() == "ISS":
        out_palette = gl_c.LOVE
    elif args.palette.upper() == "AUTO":
        out_palette = gl_c.hue_palette(comp_colours())
    elif args.palette.upper() == "COMP":
        out_palette = gl_c.hue_palette(comp_colours(c_min=-0.1, c_max=0.1))
    elif args.palette.upper() == "WHITE":
        out_palette = [(0, 0, 0)]
        out_palette += gl_c.hue_palette((random.random(),), low=128)
        out_palette.append((255, 255, 255))
    elif args.palette.upper() == "MONO":
        out_palette = gl_c.mono_palette(4)
    else:
        out_palette = gl_c.GAMENIPPER
    num_colours = len(out_palette)

    # Resize Image
    bgcolor = "rgb(%d, %d, %d)" % out_palette[0]
    image = gl_u.resize(image, args.width, args.height)
    
    # Prequantize
    image = gl_c.quantize(image, gl_c.mono_palette(num_colours * 4))

    # Create monochrome palette for quantization
    monos = gl_c.mono_palette(num_colours)

    # Dither image based on monochrome palette
    if args.dither.upper() == "FS":
        dithim = gl_d.floyd_steinberg(image, monos, mode="MONO").convert("RGB")
    elif args.dither.upper() == "BAYER":
        dithim = gl_d.bayer(image, monos, matrix=args.matrix).convert("RGB")
    else:
        dithim = gl_d.bayer(image, monos, matrix=args.matrix).convert("RGB")

    # Replace colours in image with target palette
    outim = gl_c.replace_colours(dithim, monos, out_palette)

    # Save dithered coloured image
    outim.save(args.outage)
def main():
    image = Image.open('../lenna.png').convert('L')
    image.show('Original')
    plot_histogram('Original Histogram', image)

    equalized_image = ImageOps.equalize(image)
    equalized_image.show('Equalized image')
    plot_histogram('Equalized Histogram', equalized_image)
Ejemplo n.º 11
0
    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("EqualizeHistogram 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.equalize(croppedImage.split()[0])
        croppedImage.putalpha(alpha)
        image.paste(croppedImage, 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
        # uniformly-distributed noise
        noiseArray = \
          numpy.random.randint(0, 255, croppedImage.size[0]*croppedImage.size[1])
        noiseImage = Image.new('L', croppedImage.size)
        noiseImage.putdata(noiseArray)
        compositeImage = Image.composite(croppedImage, noiseImage, alpha)
        # Equalize the composite image
        compositeImage = ImageOps.equalize(compositeImage.split()[0])
        # 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.equalize(image.split()[0])
        image.putalpha(alpha)
    return image
Ejemplo n.º 12
0
def pil_to_ascii(img, scalefactor=0.2, invert=False, equalize=True):
    """
    Generates an ascii string from a PIL image.

    Parameters
    ----------
    img : PIL.Image
        PIL image to transform.
    scalefactor : float
        ASCII characters per pixel
    invert : bool
        Invert luminance?
    equalize : bool
        equalize histogram (for best results do this)

    Returns
    -------
    str

    Examples
    --------

    >>> from asciisciit.misc import open_pil_img
    >>> img = open_pil_img("http://i.imgur.com/l2FU2J0.jpg")
    >>> text_img = pil_to_ascii(img, scalefactor=0.3)
    >>> print(text_img)

    >>> from PIL import Image
    >>> img = Image.open("some_image.png")
    >>> text_img = pil_to_ascii(img)
    >>> print(text_img)

    """
    img = img.resize((int(img.size[0]*scalefactor), 
        int(img.size[1]*scalefactor*ASPECTCORRECTIONFACTOR)),
        Image.BILINEAR)
    img = img.convert("L")  # convert to mono
    if equalize:
        img = ImageOps.equalize(img)

    if invert:
        img = ImageOps.invert(img)

    text = "\n"

    ##TODO: custom LUT
    lut = GREYSCALE_UNIFORM

    #SLOW ##TODO: USE Image.point(lut) instead
    for y in range(0, img.size[1]):
        for x in range(0, img.size[0]):
            lum = img.getpixel((x, y))
            row = bisect(BINS, lum)
            character = lut[row]
            text += character
        text += "\n"

    return text
Ejemplo n.º 13
0
def noise_steg_detect(image):
    orig_image = Image.open(image)
    equal_image = Image.open(image)
    
    equal_image = ImageOps.grayscale(equal_image)
    equal_image = ImageOps.equalize(equal_image)

    orig_image.show()
    equal_image.show()
Ejemplo n.º 14
0
def process_image(context, photo):
    if context['colorize'] or context['equalize']:
        photo = photo.convert('L')
    if context['equalize']:
        photo = ImageOps.equalize(photo)
    if context['colorize']:
        photo = ImageOps.colorize(photo, context['black'], context['white'])
    photo = photo.convert('RGBA')
    return photo
def classfiy_aHash(image1,image2,size=(8,8),exact=25):
	''' 'image1' and 'image2' is a Image Object.
	You can build it by 'Image.open(path)'.
	'Size' is parameter what the image will resize to it and then image will be compared by the algorithm.
	It's 8 * 8 when it default.  
	'exact' is parameter for limiting the Hamming code between 'image1' and 'image2',it's 25 when it default.
	The result become strict when the exact become less. 
	This function return the true when the 'image1'  and 'image2' are similar. 
	'''
	image1 = image1.resize(size).convert('L').filter(ImageFilter.BLUR)
	image1 = ImageOps.equalize(image1)
	code1 = getCode(image1, size)
	image2 = image2.resize(size).convert('L').filter(ImageFilter.BLUR)
	image2 = ImageOps.equalize(image2)
	code2 = getCode(image2, size)

	assert len(code1) == len(code2),"error"
	
	return compCode(code1, code2)<=exact
Ejemplo n.º 16
0
 def prep(self, image):
     image = image.convert("L")
     if self.size:
         image = ImageOps.fit(image, self.size, method=Image.BICUBIC)
     if self.auto_contrast:
         image = ImageOps.autocontrast(image)
     if self.equalize:
         image = ImageOps.equalize(image)
     if self.invert:
         image = ImageOps.invert(image)
     return image
Ejemplo n.º 17
0
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
Ejemplo n.º 18
0
def random_bands(sourceimg):
    """Randomly scramble color bands in image"""
    r, g, b = sourceimg.split()
    bands = [r, g, b]
    dice = [True] * 2 + [False] * 3
    random.shuffle(dice)
    if dice.pop():
        random.shuffle(bands)
    negbands = (ImageChops.invert(b) for b in bands)
    bands = [n if d else b for (b, n, d) in zip(bands, negbands, dice)]
    newimg = Image.merge('RGB', bands)
    newimg = ImageOps.equalize(newimg)
    return newimg
Ejemplo n.º 19
0
def crop_image_face(input_file, output_file, square, resize = (WIDTH, HEIGHT)):
  # Open image and adjust rectangle:
  image = Image.open(input_file)
  x, y, w, h = square
  x, y = max(x, 0), max(y, 0)
  w, h = min(w, image.size[0] - x), min(h, image.size[1] - y)

  # Crop image:
  face = image.crop((x, y, x + w, y + h))
  if resize:
    face = face.resize(resize).convert("L")
    face = ImageOps.equalize(face)
  face.save(output_file)
Ejemplo n.º 20
0
    def test_pil163(self):
        # Division by zero in equalize if < 255 pixels in image (@PIL163)

        i = hopper("RGB").resize((15, 16))

        ImageOps.equalize(i.convert("L"))
        ImageOps.equalize(i.convert("P"))
        ImageOps.equalize(i.convert("RGB"))
Ejemplo n.º 21
0
def test_pil163():
    # Division by zero in equalize if < 255 pixels in image (@PIL163)

    i = lena("RGB").resize((15, 16))

    ImageOps.equalize(i.convert("L"))
    ImageOps.equalize(i.convert("P"))
    ImageOps.equalize(i.convert("RGB"))

    success()
Ejemplo n.º 22
0
def adjustImage(image):
    """
    Returns image adjusted for facial detection.
    
    image -- input image to be adjusted
    type -- string representing adjustment type
    """
    image = Image.fromarray(image)
    #brighten
    image = image.point(lambda p: p * 1.2)
    image = ImageOps.grayscale(image)
    image = ImageOps.equalize(image)
    #image = ImageOps.autocontrast(image)

    image = ImageOps.colorize(image, (0,0,0), (255,255,255))
    return image
Ejemplo n.º 23
0
    def _pre_process_image(cls, image, bbox):
        """
        image is a PIL.Image
        bbox is x0,y0,x1,y1
        """
        # crop face if not already done so
        x0, y0, x1, y1 = bbox
        curr_width, curr_height = image.size

        if x1 <= curr_width and y1 <= curr_height:
            image = image.crop(bbox)

        image = ImageOps.grayscale(image) # convert to greyscale
        image = image.resize(cls.size, Image.ANTIALIAS) # resize to working size
        image = ImageOps.equalize(image) # equalize histogram

        return np.asarray(image.getdata())
Ejemplo n.º 24
0
def image_list(file):
    '''
    Constructs list of 8px x 12px greyscale pieces from input image
    (In order from top left to bottom right as you would read a document in most languages)
    '''
    im = Image.open(file)
    im = resize_image(im)
    im = im.convert("L")
    im = ImageOps.autocontrast(im)
    im = ImageOps.equalize(im)
    images = []
    yo = 0
    for y in range(im.size[1]/12):
        xo = 0
        for x in range(im.size[0]/8):
            image_piece = im.crop((xo,yo,8*(x+1),12*(y+1)))
            images.append(image_piece)
            xo += 8
        yo +=12
    return images
Ejemplo n.º 25
0
def main():
    parser = ArgumentParser()
    parser.add_argument("inage", metavar='INPUT', type=str)
    parser.add_argument("outage", metavar='OUTPUT', type=str)
    parser.add_argument("-d", "--dither", type=str, default="BAYER")
    parser.add_argument("-m", "--matrix", type=int, default=-2)
    parser.add_argument("-e", "--equalize", action="store_true", default=False)
    args = parser.parse_args()

    image = Image.open(args.inage)

    if args.equalize:
        image = ImageOps.equalize(image)

    # Resize Image
    image = gl_u.resize(image, 256, 192)

    # Pre-quantize image
    #image = gl_c.quantize(image, gl_c.median_cut(image, 32))
    # image = gl_d.floyd_steinberg(image, ZX_HEX)
    # image.save(args.outage)
    # exit()

    # Quantize
    # outim = gl_c.quantize(image, palette)
    outim = Image.new("RGB", image.size, "black")
    
    for x in range(256 >> 3):
        for y in range(192 >> 3):
            block = attribute_block(image, x << 3, y << 3)
            outim.paste(block, (x << 3, y << 3))
    # Dither image based on monochrome palette
    #if args.dither.upper() == "FS":
        #dithim = gl_d.floyd_steinberg(image, monos, mode="MONO").convert("RGB")
    #elif args.dither.upper() == "BAYER":
        #dithim = gl_d.bayer(image, monos, matrix=args.matrix).convert("RGB")
    #else:
        #dithim = gl_d.bayer(image, monos, matrix=args.matrix).convert("RGB")

    # Save zx-ified
    outim.save(args.outage)
Ejemplo n.º 26
0
    def __getitem__(self, index):
        img_path, mask_path, mask_weak_path = self.imgs[index]
        # print("{} and {}".format(img_path,mask_path))
        img = Image.open(img_path)  # .convert('RGB')
        mask = Image.open(mask_path)  # .convert('RGB')
        mask_weak = Image.open(mask_weak_path).convert('L')

        if self.equalize:
            img = ImageOps.equalize(img)

        if self.augmentation:
            img, mask, mask_weak = self.augment(img, mask, mask_weak)

        if self.transform:
            img = self.transform(img)
            mask = self.mask_transform(mask)
            mask = (mask == 1).long()
            # mask = self.mask_pixelvalue2OneHot(mask)
            mask_weak = self.mask_transform(mask_weak)

        return [img, mask, mask_weak, img_path]
Ejemplo n.º 27
0
    def __getitem__(self, index):
        img_path, mask_path, mask_weak_path = self.imgs[index]
        assert Path(img_path).stem == Path(mask_path).stem == Path(mask_weak_path).stem
        img = Image.open(img_path).convert('L')  # .convert('RGB')
        mask = Image.open(mask_path)  # .convert('RGB')
        mask_weak = Image.open(mask_weak_path).convert('L')

        if self.equalize:
            img = ImageOps.equalize(img)

        if self.augment is not None and self.training == ModelMode.TRAIN:
            img, mask, mask_weak = self.augment(img, mask, mask_weak)

        self.transform = self.transform if self.transform is not None else default_transform
        img = self.transform['Img'](img)
        mask = self.transform['mask'](mask)
        mask = (mask >= 0.8).long()
        mask_weak = self.transform['mask'](mask_weak)
        mask_weak = (mask_weak >= 0.8).long()

        return [img, mask, mask_weak, img_path]
Ejemplo n.º 28
0
def image_list(file):
    im = Image.open(file)

    im = resize_image(im)
    im = im.convert("L")

    im = ImageOps.autocontrast(im)
    im = ImageOps.equalize(im)

    images = []
    yo = 0
    for y in range(im.size[1]/12):
        xo = 0
        for x in range(im.size[0]/8):
            image_piece = im.crop((xo,yo,8*(x+1),12*(y+1)))

            images.append(image_piece)

            xo += 8
        yo +=12
    return images
Ejemplo n.º 29
0
def poison_scenario_preprocessing(batch):
    img_size = 48
    img_out = []
    quantization = 255.0
    for im in batch:
        img_eq = ImageOps.equalize(Image.fromarray(im))
        width, height = img_eq.size
        min_side = min(img_eq.size)
        center = width // 2, height // 2

        left = center[0] - min_side // 2
        top = center[1] - min_side // 2
        right = center[0] + min_side // 2
        bottom = center[1] + min_side // 2

        img_eq = img_eq.crop((left, top, right, bottom))
        img_eq = np.array(img_eq.resize([img_size, img_size])) / quantization

        img_out.append(img_eq)

    return np.array(img_out, dtype=np.float32)
Ejemplo n.º 30
0
    def read_image(self, image_info):
        """Read from ppm image and return a ndarray with size [1, self.IMAGE_SIZE * self.IMAGE_SIZE + 1],
        in which the last element is the label."""
        im = Image.open(image_info['path'])
        im = im.crop(image_info['box'])

        if self.ignore_small and (im.size[0] < self.IMAGE_SIZE or im.size[1] < self.IMAGE_SIZE):
            return None

        im = im.convert('L')
        im = im.resize((self.IMAGE_SIZE, self.IMAGE_SIZE))
        im = ImageOps.equalize(im)
        data = im.tobytes()
        data = np.fromstring(data, dtype=np.uint8)
        data = np.append(data, [image_info['label']])

        size = data.shape[0]

        data = np.reshape(data, [1, size])

        return data
Ejemplo n.º 31
0
def split_normalize(image):
    """Splitting source image then normalize it.
    
    :param image: source image
    :return: blue and green channel
    """
    im = Image.Image.split(image)
    g = ImageOps.equalize(im[1], mask = None)
    mean = Stat(im[2]).mean[0]
    b = np.array(im[2]).astype('float32')
    b /= (1.0 + mean) 
    mean = Stat(g).mean[0]
    g = np.array(g).astype('float32')
    g /= (1.0 + mean)
    b = np.clip(b, 0, 1)
    g = np.clip(g, 0, 1)
    b *= 255.0
    g *= 255.0
    b = Image.fromarray(b.astype('uint8'))
    g = Image.fromarray(g.astype('uint8'))
    return b, g
Ejemplo n.º 32
0
def expand_tocolor(pil_image: PIL.Image,
                   alpha: float = 1.2,
                   beta: float = 1.0,
                   equalize: bool = True) -> PIL.Image:
    if equalize:
        pil_image = ImageOps.equalize(pil_image)

    pil_image = pil_image.convert('L')
    imgarray = np.asarray(pil_image)
    # gray = np.array((imgarray[:, :,  0] * 3. * alpha) ** beta, dtype=np.float32)
    gray = np.array((imgarray * 3. * alpha) ** beta, dtype=np.float32)
    enhanced_B = gray.copy()
    enhanced_B[enhanced_B > 254] = 254
    enhanced_G = (gray - 250)
    enhanced_G[enhanced_G > 254] = 254
    enhanced_G[enhanced_G <= 40] = 40
    enhanced_R = (gray - 510)
    enhanced_R[enhanced_R <= 20] = 20
    enhanced_R[enhanced_R > 254] = 254
    enhanced_RGB = np.dstack((enhanced_R, enhanced_G, enhanced_B)).astype(np.uint8)
    enhanced_color = PIL.Image.fromarray(enhanced_RGB)
    return enhanced_color
    def __init__(self, p1, operation1, magnitude_idx1, p2, operation2, magnitude_idx2, fillcolor=(128, 128, 128)):
        ranges = {
            "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 = {
            "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.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 enhance_images(sharpness,contrast,glacier):
    #-- directory setup
    #- current directory
    current_dir = os.path.dirname(os.path.realpath(__file__))
    main_dir = os.path.join(current_dir,'..','FrontLearning_data')
    glacier_ddir = os.path.join(main_dir,'%s.dir'%glacier)
    data_dir = os.path.join(glacier_ddir, 'data')
    trn_dir = os.path.join(data_dir,'train')
    tst_dir = os.path.join(data_dir,'test')

    #-- first read data
    images,names = load_data(trn_dir,tst_dir)
    #-- make output directory dictionary
    outdir = {}
    outdir['train'] = os.path.join(trn_dir,'images_equalize_autocontrast_smooth_edgeEnhance')
    outdir['test'] = os.path.join(tst_dir,'images_equalize_autocontrast_smooth_edgeEnhance')
    #-- loop through train and test data
    for t in ['test']:#,'train']:
        if (not os.path.isdir(outdir[t])):
            os.mkdir(outdir[t])
        #-- loop through images and ehnance
        for m,n in zip(images[t],names[t]):
            #-- first blur the images to get rid of all the noise
            '''
            sharp_obj = ImageEnhance.Sharpness(m)
            blurred = sharp_obj.enhance(sharpness)
            contr_obj = ImageEnhance.Contrast(blurred)
            final = contr_obj.enhance(contrast)
            
            contr_obj = ImageEnhance.Contrast(m)
            im = contr_obj.enhance(contrast)
            final = im.filter(ImageFilter.SMOOTH)#.filter(ImageFilter.EDGE_ENHANCE)
            '''
    
            final = ImageOps.equalize(ImageOps.autocontrast(m.convert('L'))).filter(ImageFilter.SMOOTH).filter(ImageFilter.EDGE_ENHANCE)


            #-- write image to file
            final.save(os.path.join(outdir[t],'%s'%n))
Ejemplo n.º 35
0
    def __getitem__(self, index):
        fat_path, inn_path,opp_path,wat_path,mask_path = self.imgs[index]

        img_f = Image.open(fat_path)#.convert('L')
        img_i = Image.open(inn_path)#.convert('L')
        img_o = Image.open(opp_path)#.convert('L')
        img_w = Image.open(wat_path)#.convert('L')
        mask = Image.open(mask_path).convert('L')
        
        if self.equalize:
            img = ImageOps.equalize(img)

        if self.augmentation:
            img, mask = self.augment(img, mask)

        if self.transform:
            img_f = self.transform(img_f)
            img_i = self.transform(img_i)
            img_o = self.transform(img_o)
            img_w = self.transform(img_w)
            mask = self.mask_transform(mask)

        return [img_f,img_i,img_o,img_w, mask, fat_path]
Ejemplo n.º 36
0
def v_sivinsko(slika, autokontrast=False, izravnava=False):
    """Sliko pretvori v sivinski barvni prostor.

    Args:
        slika: (object): PIL/Pillow objekt slike
        autokontrast (bool): Avtomatsko popravi kontrast slike. (Default: False)
        izravnava (bool): Skuša izravati histogram slike. (Default: False)

    Returns:
        object: PIL/Pillow objekt

    """
    _slika = slika.copy()
    if _slika.mode != 'L':
        _slika.convert('L')

    if autokontrast:
        _slika = ImageOps.autocontrast(_slika)

    if izravnava:
        _slika = ImageOps.equalize(_slika)

    return _slika
Ejemplo n.º 37
0
def imageprocess(String2, int2):
    pil_im = Image.open("images/" + String2).convert(
        'L')  #opens said image converts to greyscale

    halfwidth = pil_im.size[
        0] / 2  #right now I crop from the center of the image
    halfheight = pil_im.size[
        1] / 2  #these two lines find the location we are cropping from, right now dead center

    twoThirdwidth = pil_im.size[
        0] / 1.25  #not actually 2/3rds anymore but... whatever
    twoThirdheight = pil_im.size[
        1] / 2.25  #These two lines decide how much of the image we get

    pil_im = pil_im.crop((
        halfwidth - twoThirdwidth,  #crop
        halfheight - twoThirdheight,
        halfwidth + twoThirdwidth,  #that
        halfheight + twoThirdheight,
    )  #shit
                         )

    pil_im = array(pil_im)  # convert the image to an array
    pil_im = (
        100.0 / 255
    ) * pil_im + 100  #clamp the values... this might be changed a bit to offer more grey levels ( may provide higher contrast)
    pil_im = 255.0 * (pil_im / 255.0)**2  #quadratic transformation

    pil_im = Image.fromarray(
        uint8(pil_im)
    )  #in order to do the equalization the easy way, we need an image not an array
    pil_im = ImageOps.equalize(pil_im)  #equalize that shit

    String2 = 'images/newpicture0'  #save transformed image as newpicture#
    String2 = String2 + str(int2)
    pil_im.save(String2 + '.jpg')
    return
Ejemplo n.º 38
0
async def deepfry(ctx, quality=None, image_url=None):
    """Deep fries an image"""
    channel = ctx.message.channel
    if image_url == None:
        image_url = await check_pictures(channel)
    # Need to use requests to read the image otherwise it returns a 403:FORBIDDEN error
    response = requests.get(image_url)
    img = Image.open(BytesIO(response.content))  # Reading the raw image data
    img = img.convert('RGB')

    # Resizes and resamples the image multiple times, then crushes the histogram
    if quality == 'crush':
        width, height = img.width, img.height
        img = img.resize((int(width ** .75), int(height ** .75)),
                         resample=Image.LANCZOS)
        img = img.resize((int(width ** .88), int(height ** .88)),
                         resample=Image.BILINEAR)
        img = img.resize((int(width ** .9), int(height ** .9)),
                         resample=Image.BICUBIC)
        img = img.resize((width, height), resample=Image.BICUBIC)
        img = ImageOps.posterize(img, 5)

    # Deep fries the image
    sharpness = ImageEnhance.Sharpness(img)
    img = sharpness.enhance(70)  # Sharpness
    brightnesss = ImageEnhance.Brightness(img)
    img = brightnesss.enhance(2)  # Brightness
    saturation = ImageEnhance.Color(img)
    img = saturation.enhance(2)  # Saturation
    contrast = ImageEnhance.Contrast(img)
    img = contrast.enhance(3)  # Contrast
    img = img.filter(ImageFilter.SMOOTH_MORE)
    img = ImageOps.equalize(img)

    img.save(fp=f'fried.jpg', format='JPEG', quality=8)
    await client.send_file(channel, 'fried.jpg')
    os.remove('fried.jpg')
Ejemplo n.º 39
0
def process_image(image):

    if make_decision(85):
        image = ImageOps.grayscale(image)
        image = ImageOps.colorize(image, get_random_hex_color(),
                                  get_random_hex_color(),
                                  get_random_hex_color())
    # if with_decision(50):
    #     image = ImageOps.flip(image)
    # if with_decision(50):
    #     image = ImageOps.mirror(image)
    if make_decision(50):
        posterize_bits = random.randrange(1, 8)
        image = ImageOps.posterize(image, posterize_bits)
    if make_decision(50):
        threshold = random.randrange(0, 255)
        image = ImageOps.solarize(image, threshold)
    if make_decision(50):
        image = ImageOps.equalize(image)
    if make_decision(50):
        blur_radius = random.randrange(0, 3)
        image = image.filter(ImageFilter.GaussianBlur(blur_radius))

    return image
Ejemplo n.º 40
0
def histeq(im,nbr_bins=256):
    '''
    TODO:
    - use local method.
    
    Old version
    
    # get image histogram
    imhist,bins = histogram(im.flatten(),nbr_bins,normed=False)
    cdf = imhist.cumsum() # cumulative distribution function
    cdf = 255 * cdf / cdf[-1] # normalize
    # use linear interpolation of cdf to find new pixel values
    im2 = interp(im.flatten(),bins[:-1],cdf)
    im = im2.reshape(im.shape)
    '''
    if type(im) is not Image:
        im = Image.fromarray(im)
        
    im = ImageOps.equalize(im)
    
    if type(im) is not np.ndarray:
        im = np.array(im)
    
    return im
Ejemplo n.º 41
0
def im_gamma_equalize(f_path, fname):
    file_path = os.path.join(f_path, fname)

    # 画像ファイルを取り込んで RGB を確保。
    im = Image.open(file_path)
    im = im.convert("RGB")

    # ガンマ補正を解除して RGB=>YCbCr 変換
    # Y だけガンマ補正をかけ直す。
    im = _gamma_correction(im, 1 / 2.2)
    im = im.convert("YCbCr")
    yy, cb, cr = im.split()  # linear yy,cc,cr
    yy = _gamma_correction(yy, 2.2)

    # 輝度に対してヒストグラム平坦化
    yy = ImageOps.equalize(yy)

    # Y のガンマ補正を解除して YCbCR=>RGB 変換
    # RGB にガンマ補正を掛け直す
    yy = _gamma_correction(yy, 1 / 2.2)
    im = Image.merge("YCbCr", (yy, cb, cr))
    im = im.convert("RGB")

    return np.array(_gamma_correction(im, 2.2))
Ejemplo n.º 42
0
def random_image(sourceimg=None, size=(200, 100)):
    """Scramble source image to create placeholder image"""
    if sourceimg is None:
        sourceimg = Image.open(str(SOURCE_IMG))
    width, height = size
    sqrt2 = 2**.5
    regionsize = int(min(
        max(width, height) * sqrt2,
        min(sourceimg.size),
    ))
    inscribed = int(regionsize / sqrt2)
    x = random.randint(0, sourceimg.width - regionsize)
    y = random.randint(0, sourceimg.height - regionsize)
    subsection = sourceimg.crop([x, y, x + regionsize, y + regionsize])
    angle = random.randint(0, 360)
    rotated = subsection.rotate(angle)
    ratio = width / height
    if ratio > 1:
        cw, ch = inscribed, inscribed / ratio
    else:
        cw, ch = inscribed * ratio, inscribed
    cropbox = (
        (regionsize - cw) / 2,
        (regionsize - ch) / 2,
        (regionsize + cw) / 2,
        (regionsize + ch) / 2,
    )
    cropped = rotated.crop(cropbox)
    blur = ImageFilter.GaussianBlur(1)
    result = cropped.resize((width, height))
    enhanced = result.filter(blur)
    enhanced = random_bands(enhanced)
    blended = ImageChops.blend(result, enhanced, 0.5)
    blended = ImageChops.blend(blended, ImageOps.equalize(blended), 0.5)
    blended = blended.filter(blur)
    return blended
Ejemplo n.º 43
0
def image_to_hash( path_to_image ):
    """takes an image and returns its hash"""

    encStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    size = 18, 14
    #size = 24, 16

    bw = Image.open( path_to_image ) 
    bw = bw.convert('L')
    bw = ImageOps.equalize(bw)
    bw = bw.point(lambda x: 0 if x<128 else 255, '1')
    bw = ImageOps.fit(bw, size, Image.ANTIALIAS)
    bw.save( "smally.jpg", "JPEG")

    pixels = bw.load()

    matrix = []
    for row in range(size[1]):
        vector = []
        for col in range(size[0]):
            color = pixels[col, row]
            if color == 255:
                color = 1
            vector.append( color )
        matrix.append( vector )

    imHash = ""
    imHash += encStr[ int( size[0] / 6 ) ]
    for row in matrix:
        symbols = [ row[i:i + 6] for i in range(0, size[0], 6) ]
        for symbol in symbols:
            bin = "".join( str(x) for x in symbol )
            number = int( bin, 2 )
            char = encStr[ number ]
            imHash += char
    return imHash
Ejemplo n.º 44
0
def RGBComposite(TileName,Tm,TileDir,OutDir):
    st = time.time()
    #L2A_201912_T49RGQ_20200426T222639_R10m_NIR
    R = glob.glob(os.path.join(TileDir,'L2A_{}_{}_*_R60m_B04.tif').format(Tm,TileName))[0]
    G = glob.glob(os.path.join(TileDir, 'L2A_{}_{}_*_R60m_B03.tif').format(Tm,TileName))[0]
    B = glob.glob(os.path.join(TileDir, 'L2A_{}_{}_*_R60m_B02.tif').format(Tm,TileName))[0]

    assert os.path.exists(R),"no file name {} exists".format(R)
    assert os.path.exists(G), "no file name {} exists".format(G)
    assert os.path.exists(B), "no file name {} exists".format(B)


    Rr = gdal.Open(R)
    Gr = gdal.Open(G)
    Br = gdal.Open(B)
    proj = Rr.GetProjection()
    geotrans = Rr.GetGeoTransform()
    basename = os.path.basename(R).split("_")
    Name = basename[0]+'_'+basename[1]+'_'+basename[2]+'_'+basename[4]+'_'+'RGB'+'.tif'
    Path = os.path.join(OutDir,Name)
    Size = Rr.RasterXSize
    Data = np.zeros(shape=(Size,Size,3))
    Data[:,:,0] = Rr.ReadAsArray()*0.0255
    del Rr
    Data[:, :, 1] = Gr.ReadAsArray()*0.0255
    del Gr
    Data[:, :, 2] = Br.ReadAsArray()*0.0255
    del Br

    Data = Image.fromarray(np.uint8(Data))
    Data =ImageOps.equalize(Data)

    write_Img(Data, Path, proj, geotrans, 1830, 1830, im_bands=3, dtype=gdal.GDT_Byte)
    del Data
    end = time.time()
    print(end - st)
Ejemplo n.º 45
0
def save_image(array, name, enhance=False):
    """saves 2d array of values 0-1 to a grayscale PNG"""

    if (array is None) or array.count() == 0:
        return

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    from PIL import Image, ImageOps

    if not os.path.isdir(settings.PNG_DIR):
        os.makedirs(settings.PNG_DIR)

    png = os.path.join(settings.PNG_DIR, str(name) + '.png')
    logger.debug('writing {}'.format(png))

    array = plt.cm.jet(array) * 255
    array = array.astype(np.uint8)
    image = Image.fromarray(array)
    if enhance:
        image = ImageOps.equalize(image)
        image = ImageOps.autocontrast(image)
    image.save(png)
Ejemplo n.º 46
0
def save_image(array, name, enhance=False):
    """saves 2d array of values 0-1 to a grayscale PNG"""

    if (array is None) or array.count() == 0:
        return

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    from PIL import Image, ImageOps

    if not os.path.isdir(settings.PNG_DIR):
        os.makedirs(settings.PNG_DIR)

    png = os.path.join(settings.PNG_DIR, str(name) + '.png')
    logger.debug('writing {}'.format(png))

    array = plt.cm.jet(array) * 255
    array = array.astype(np.uint8)
    image = Image.fromarray(array)
    if enhance:
        image = ImageOps.equalize(image)
        image = ImageOps.autocontrast(image)
    image.save(png)
Ejemplo n.º 47
0
def random_image(sourceimg=None, size=(200, 100)):
    """Scramble source image to create placeholder image"""
    if sourceimg is None:
        sourceimg = Image.open(str(SOURCE_IMG))
    width, height = size
    sqrt2 = 2**.5
    regionsize = int(min(
        max(width, height) * sqrt2,
        min(sourceimg.size),
    ))
    inscribed = int(regionsize / sqrt2)
    x = random.randint(0, sourceimg.width - regionsize)
    y = random.randint(0, sourceimg.height - regionsize)
    subsection = sourceimg.crop([x, y, x + regionsize, y + regionsize])
    angle = random.randint(0, 360)
    rotated = subsection.rotate(angle)
    ratio = width / height
    if ratio > 1:
        cw, ch = inscribed, inscribed / ratio
    else:
        cw, ch = inscribed * ratio, inscribed
    cropbox = (
        (regionsize - cw) / 2,
        (regionsize - ch) / 2,
        (regionsize + cw) / 2,
        (regionsize + ch) / 2,
    )
    cropped = rotated.crop(cropbox)
    blur = ImageFilter.GaussianBlur(1)
    result = cropped.resize((width, height))
    enhanced = result.filter(blur)
    enhanced = random_bands(enhanced)
    blended = ImageChops.blend(result, enhanced, 0.5)
    blended = ImageChops.blend(blended, ImageOps.equalize(blended), 0.5)
    blended = blended.filter(blur)
    return blended
Ejemplo n.º 48
0
def m3():
    Image.MAX_IMAGE_PIXELS = None
    for fn in os.listdir("all"):
        if fn.endswith("TIF"):
            adj_fn = fn.split("_B")[1]
            if len(adj_fn) == 5:
                adj_fn = "0" + adj_fn
            adj_fn = "edited/A_" + adj_fn
            print(adj_fn)

            im = Image.open("all/" + fn)
            print(im.format, im.size, im.mode)

            if fn.endswith("8.TIF"):
                box = (800 * 2, 3500 * 2, 1200 * 2, 3900 * 2)
                region = im.crop(box)
            else:
                box = (800, 3500, 1200, 3900)
                region = im.crop(box)
                region = region.resize((800, 800))

            region = ImageOps.equalize(region)
            region.save(adj_fn)
            print(region.size)
Ejemplo n.º 49
0
 def equalize(self, image, params):
     return ImageOps.equalize(image)
Ejemplo n.º 50
0
def equalize(img, **__):
    return ImageOps.equalize(img)
from PIL import Image
from PIL import ImageOps
import matplotlib.pyplot as plt
img = Image.open("/home/abes/Desktop/aa.jpeg")
plt.figure(0)
plt.subplot(223)
plt.xlabel('Image Histogram')
plt.imshow(img)
gs_image = ImageOps.grayscale(img)
hist = gs_image.histogram()
for i in range(0, 256):
    plt.bar(i, hist[i])
plt.subplot(222)
plt.xlabel('histogram equilised image')
hist_eq = ImageOps.equalize(gs_image)
plt.imshow(hist_eq)
plt.subplot(224)
plt.xlabel('histogram equalization')
histeq = list(hist_eq.getdata())
for i in range(0, 256):
    plt.bar(i, histeq[i])
plt.show()
Ejemplo n.º 52
0
 def transform(self, pil_img, label, **kwargs):
     return ImageOps.equalize(pil_img), label
Ejemplo n.º 53
0
def equalize(img, v):
    '''
    {'method': 'equalize'}
    '''

    return ImageOps.equalize(img)
Ejemplo n.º 54
0
def Equalize(self):
    img = Image.open(self, 'r')
    im_e = ImageOps.equalize(img)
    im_e.save(O_REAL_PATH, "JPEG", quality=100, optimize=True)
    img.close()
Ejemplo n.º 55
0
def normalized(img):
    if isinstance(img, np.ndarray):
        processed_img = ImageOps.equalize(PILImage.fromarray(img, mode='RGB'))
    else:
        processed_img = ImageOps.equalize(img)
    return processed_img
Ejemplo n.º 56
0
def equalize(img):
    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
    return ImageOps.equalize(img)
Ejemplo n.º 57
0
def run(dir_in,
        fn_out,
        cal_dir=None,
        hist_eq=True,
        invert=True,
        hist_eq_roi=None,
        scalar=None,
        rescale=True,
        bpr=True,
        raw=False):
    if not fn_out:
        dir_in = dir_in
        if dir_in[-1] == '/':
            dir_in = dir_in[:-1]
        fn_out = dir_in + '.png'
        fn_oute = dir_in + '_e.png'
    else:
        fn_out = fn_out
        fn_oute = fn_out

    _imgn, img_in = im_util.average_dir(dir_in, scalar=scalar)

    desc = dir_in
    print('Processing %s' % desc)

    im_wip = img_in
    print("Avg min: %u, max: %u" %
          (np.ndarray.min(np.array(im_wip)), np.ndarray.max(np.array(im_wip))))
    if not raw:
        if not cal_dir:
            cal_dir = im_util.default_cal_dir(im_dir=dir_in)
            if not os.path.exists(cal_dir):
                print("WARNING: default calibration dir %s does not exist" %
                      cal_dir)
                cal_dir = None

        if cal_dir:
            assert os.path.exists(cal_dir)
            print("Found calibration files at %s" % cal_dir)

        if rescale and cal_dir:
            ffimg = Image.open(os.path.join(cal_dir, 'ff.png'))
            np_ff2 = np.array(ffimg)
            dfimg = Image.open(os.path.join(cal_dir, 'df.png'))
            np_df2 = np.array(dfimg)

            # ff *should* be brighter than df
            # (due to .png pixel value inversion convention)
            mins = np.minimum(np_df2, np_ff2)
            maxs = np.maximum(np_df2, np_ff2)

            u16_mins = np.full(mins.shape, 0x0000, dtype=np.dtype('float'))
            u16_ones = np.full(mins.shape, 0x0001, dtype=np.dtype('float'))
            u16_maxs = np.full(mins.shape, 0xFFFF, dtype=np.dtype('float'))

            cal_det = maxs - mins
            # Prevent div 0 on bad pixels
            cal_det = np.maximum(cal_det, u16_ones)
            cal_scalar = 0xFFFF / cal_det

            np_in2 = np.array(im_wip)
            np_scaled = (np_in2 - mins) * cal_scalar
            # If it clipped, squish to good values
            np_scaled = np.minimum(np_scaled, u16_maxs)
            np_scaled = np.maximum(np_scaled, u16_mins)
            im_wip = Image.fromarray(np_scaled).convert("I")
            print("Rescale min: %u, max: %u" % (np.ndarray.min(
                np.array(im_wip)), np.ndarray.max(np.array(im_wip))))

        # Seems this needs to be done after scaling or artifacts get amplified
        if bpr and cal_dir:
            badimg = Image.open(os.path.join(cal_dir, 'bad.png'))
            im_wip = im_util.do_bpr(im_wip, badimg)
            print("BPR min: %u, max: %u" % (np.ndarray.min(
                np.array(im_wip)), np.ndarray.max(np.array(im_wip))))

        if invert:
            # IOError("not supported for this image mode")
            # im_wip = ImageOps.invert(im_wip)
            im_wip = im_util.im_inv16_slow(im_wip)
            print("Invert min: %u, max: %u" % (np.ndarray.min(
                np.array(im_wip)), np.ndarray.max(np.array(im_wip))))
    print("Save %s" % fn_out)
    im_wip.save(fn_out)

    # https://stackoverflow.com/questions/43569566/adaptive-histogram-equalization-in-python
    # simple implementation
    # CV2 might also work

    if hist_eq:
        mode = os.getenv("FAXITRON_EQ_MODE", "0")
        print("Eq mode (FAXITRON_EQ_MODE) %s" % mode)
        if mode == "0":
            if hist_eq_roi:
                x1, y1, x2, y2 = hist_eq_roi
                ref_im = im_wip.crop((x1, y1, x2, y2))
            else:
                ref_im = im_wip

            ref_np2 = np.array(ref_im)
            wip_np2 = np.array(im_wip)
            wip_np2 = im_util.histeq_np_apply(
                wip_np2, im_util.histeq_np_create(ref_np2))
            im_wip = im_util.npf2im(wip_np2)
        elif mode == "convert":
            with util.AutoTempFN(suffix='.png') as tmpa:
                with util.AutoTempFN(suffix='.png') as tmpb:
                    im_wip.save(tmpa)
                    subprocess.check_call(
                        "convert %s \( +clone -equalize \) -average %s" %
                        (tmpa, tmpb),
                        shell=True)
                    im_wip = Image.open(tmpb)
        elif mode == "1":
            # OSError: not supported for this image mode
            im_wip = ImageOps.equalize(im_wip, mask=None)
        elif mode == "2":
            imnp = np.array(im_wip, dtype=np.uint16)
            im_wip = im_util.npf2im(exposure.equalize_hist(imnp))
        elif mode == "3":
            # raise ValueError("Images of type float must be between -1 and 1.")
            imnp = np.array(im_wip, dtype=np.uint16)
            #imnp = np.ndarray.astype(imnp, dtype=np.float)
            print(np.ndarray.min(imnp), np.ndarray.max(imnp))
            imnp = 1.0 * imnp / 0xFFFF
            im_wip = im_util.npf2im(
                exposure.equalize_adapthist(imnp, clip_limit=0.03))
        else:
            raise Exception(mode)
        print("Save %s" % fn_oute)
        im_wip.save(fn_oute)
        print("Eq min: %u, max: %u" % (np.ndarray.min(
            np.array(im_wip)), np.ndarray.max(np.array(im_wip))))
Ejemplo n.º 58
0
 def _imequalize(img):
     # equalize the image using PIL.ImageOps.equalize
     from PIL import ImageOps, Image
     img = Image.fromarray(img)
     equalized_img = np.asarray(ImageOps.equalize(img))
     return equalized_img
Ejemplo n.º 59
0
def equalize(pil_image: PIL.Image) -> PIL.Image:
    return ImageOps.equalize(pil_image)
Ejemplo n.º 60
-1
    def test_sanity(self):

        ImageOps.autocontrast(hopper("L"))
        ImageOps.autocontrast(hopper("RGB"))

        ImageOps.autocontrast(hopper("L"), cutoff=10)
        ImageOps.autocontrast(hopper("L"), ignore=[0, 255])

        ImageOps.autocontrast_preserve(hopper("L"))
        ImageOps.autocontrast_preserve(hopper("RGB"))

        ImageOps.autocontrast_preserve(hopper("L"), cutoff=10)
        ImageOps.autocontrast_preserve(hopper("L"), ignore=[0, 255])

        ImageOps.colorize(hopper("L"), (0, 0, 0), (255, 255, 255))
        ImageOps.colorize(hopper("L"), "black", "white")

        ImageOps.crop(hopper("L"), 1)
        ImageOps.crop(hopper("RGB"), 1)

        ImageOps.deform(hopper("L"), self.deformer)
        ImageOps.deform(hopper("RGB"), self.deformer)

        ImageOps.equalize(hopper("L"))
        ImageOps.equalize(hopper("RGB"))

        ImageOps.expand(hopper("L"), 1)
        ImageOps.expand(hopper("RGB"), 1)
        ImageOps.expand(hopper("L"), 2, "blue")
        ImageOps.expand(hopper("RGB"), 2, "blue")

        ImageOps.fit(hopper("L"), (128, 128))
        ImageOps.fit(hopper("RGB"), (128, 128))

        ImageOps.flip(hopper("L"))
        ImageOps.flip(hopper("RGB"))

        ImageOps.grayscale(hopper("L"))
        ImageOps.grayscale(hopper("RGB"))

        ImageOps.invert(hopper("L"))
        ImageOps.invert(hopper("RGB"))

        ImageOps.mirror(hopper("L"))
        ImageOps.mirror(hopper("RGB"))

        ImageOps.posterize(hopper("L"), 4)
        ImageOps.posterize(hopper("RGB"), 4)

        ImageOps.solarize(hopper("L"))
        ImageOps.solarize(hopper("RGB"))