def Anaglyph(imgl, imgr, angle):
	right = imgr
	left = imgl
	width, height = left.size
	leftMap = left.load()
	rightMap = right.load()

	if angle == 'parallel':
		left = grayscale(left)
		#left = colorize(left, (0,0,0),(0,255,255))

		right = grayscale(right)
		#right = colorize(right, (0,0,0),(255,0,0))

	if angle == 'toedin':
		left = grayscale(left)
		left = colorize(left, (0,0,0),(255,0,0))

		right = grayscale(right)
		right = colorize(right, (0,0,0),(0,255,255))

	list_out = []
	for red, cyan in itertools.izip(list(left.getdata()), list(right.getdata())):
		list_out.append(min(red, 255))
		list_out.append(min(cyan, 255))
		list_out.append(min(cyan, 255))

	return list_out
Example #2
0
def correct_coords(apps, page: Page, chars: Character) -> None:
    PageMultiplier = apps.get_model('calligraphy', 'PageMultiplier')
    print(str(page.image))
    p_img = grayscale(Image.open(str(page.image)))
    mypage = page_dat(page.image_width, page.image_length, p_img, page)
    mychars = []
    for char in chars:
        coords = str(char.image).split('(')[1].split(')')[0].split(',')
        charimg = autocontrast(grayscale(Image.open(str(char.image))))
        mychars.append(char_dat(coords, charimg, char))
    find_search_space(PageMultiplier, mypage, mychars)
Example #3
0
def generate_imgs_from_src(fg_path, bg_path, num=10):
    fg = grayscale(Image.open(fg_path))
    fg = fg.resize((32, 32))
    fg.load()
    fg = np.asarray(fg, dtype="int32")

    bg = grayscale(Image.open(bg_path))
    bg.load()
    bg = np.asarray(bg, dtype="int32")

    return generate_images(fg, bg, num)
Example #4
0
def convert_page(page, width=WIDTH, height=HEIGHT, double=False):
    if double:
        width *= 2
        height *= 2
    amp = True
    scale = 1.0
    while amp:
        matrix = fitz.Matrix(scale, scale)
        pix_width,pix_height=list([(p.w,p.h)for p in\
                                   [page.get_pixmap(alpa=False,
                                                    matrix=matrix)]][0])
        if pix_width > width:
            amp = False
        else:
            scale += 1
    page.get_pixmap(alpa=False, matrix=matrix).writePNG('temp.ppm')
    img = grayscale(Image.open('temp.ppm'))
    os.remove('temp.ppm')
    down = width / img.width
    rw = int(down * img.width)
    rh = int(down * img.height)
    img_resized = img.resize((rw, rh))
    if img_resized.height > height:
        down = height / img.height
        rw = int(down * img.width)
        rh = int(down * img.height)
        img_resized = img.resize((rw, rh))
    return (img_resized)
def image_tint(src, tint='#ffffff'):
    src = Image.open(src).convert('RGBA')
    r, g, b, alpha = src.split()
    gray = grayscale(src)
    result = colorize(gray, (0, 0, 0, 0), tint)
    result.putalpha(alpha)
    return result
Example #6
0
    def image_tint(self, source_path, tint='#ffffff'):
        '''
        Take an image from a path and convert it to a tinted string for sprite coloration.
        :param source_path: sting path to image
        :param tint: string color code in hex
        :return: string of modified image
        '''

        img_source = Image.open(source_path)                # Get the image from specified path
        tint_red, tint_green, tint_blue = getrgb(tint)      # Get color tint of each color
        tint_lum = getcolor(tint, "L")                      # Tint color luminosity

        if tint_lum == 0:   # Avoid division by 0
            tint_lum = 1

        tint_lum = float(tint_lum)  # Compute luminosity preserving tint factors
        sr, sg, sb = map(lambda tv: tv / tint_lum, (tint_red, tint_green, tint_blue))  # per component adjustments

        # create look-up tables to map luminosity to adjusted tint
        # (using floating-point math only to compute table)
        luts = (list(map(lambda lr: int(lr * sr + 0.5), range(256))) +
                list(map(lambda lg: int(lg * sg + 0.5), range(256))) +
                list(map(lambda lb: int(lb * sb + 0.5), range(256))))

        l = grayscale(img_source)  # 8-bit luminosity version of whole image

        if Image.getmodebands(img_source.mode) < 4:
            merge_args = (img_source.mode, (l, l, l))  # for RGB verion of grayscale
        else:  # include copy of img_source image's alpha layer
            a = Image.new("L", img_source.size)
            a.putdata(img_source.getdata(3))
            merge_args = (img_source.mode, (l, l, l, a))  # for RGBA verion of grayscale
            luts += range(256)  # for 1:1 mapping of copied alpha values

        return Image.merge(*merge_args).point(luts)     # Return string of image
Example #7
0
def image_tint(src, tint='#fffab5'):
    if Image.isStringType(src):  # file path?
        src = Image.open(src)
    if src.mode not in ['RGB', 'RGBA']:
        raise TypeError('Unsupported source image mode: {}'.format(src.mode))
    src.load()

    tr, tg, tb = getrgb(tint)
    tl = getcolor(tint, "L")  # tint color's overall luminosity
    if not tl: tl = 1  # avoid division by zero
    tl = float(tl)  # compute luminosity preserving tint factors
    sr, sg, sb = map(lambda tv: tv/tl, (tr, tg, tb))  # per component
                                                      # adjustments
    # create look-up tables to map luminosity to adjusted tint
    # (using floating-point math only to compute table)
    luts = (tuple(map(lambda lr: int(lr*sr + 0.5), range(256))) +
            tuple(map(lambda lg: int(lg*sg + 0.5), range(256))) +
            tuple(map(lambda lb: int(lb*sb + 0.5), range(256))))
    l = grayscale(src)  # 8-bit luminosity version of whole image
    if Image.getmodebands(src.mode) < 4:
        merge_args = (src.mode, (l, l, l))  # for RGB verion of grayscale
    else:  # include copy of src image's alpha layer
        a = Image.new("L", src.size)
        a.putdata(src.getdata(3))
        merge_args = (src.mode, (l, l, l, a))  # for RGBA verion of grayscale
        luts += tuple(range(256))  # for 1:1 mapping of copied alpha values
    return Image.merge(*merge_args).point(luts)
Example #8
0
def find_mount_boundary_quad(flipped_image, threshold):
    gray_image = grayscale(flipped_image)
    top_boundary_start, top_boundary_end = find_mount_top_boundary(
        gray_image, threshold)
    bottom_boundary_start, bottom_boundary_end = find_mount_bottom_boundary(
        gray_image, threshold)
    left_boundary_start, left_boundary_end = find_mount_left_boundary(
        gray_image, threshold)
    right_boundary_start, right_boundary_end = find_mount_right_boundary(
        gray_image, threshold)
    top_boundary_line = Line2.through_points(top_boundary_start,
                                             top_boundary_end)
    bottom_boundary_line = Line2.through_points(bottom_boundary_start,
                                                bottom_boundary_end)
    left_boundary_line = Line2.through_points(left_boundary_start,
                                              left_boundary_end)
    right_boundary_line = Line2.through_points(right_boundary_start,
                                               right_boundary_end)
    top_left_corner = intersection2(top_boundary_line, left_boundary_line)
    top_right_corner = intersection2(top_boundary_line, right_boundary_line)
    bottom_left_corner = intersection2(bottom_boundary_line,
                                       left_boundary_line)
    bottom_right_corner = intersection2(bottom_boundary_line,
                                        right_boundary_line)
    print(top_left_corner)
    print(top_right_corner)
    print(bottom_left_corner)
    print(bottom_right_corner)
    return top_left_corner, top_right_corner, bottom_right_corner, bottom_left_corner
Example #9
0
def image_tint(path: str, tint: str) -> Image:
    src = Image.open(path)
    if src.mode not in ("RGB", "RGBA"):
        raise TypeError(f"Unsupported source image mode: {src.mode}")
    src.load()

    tr, tg, tb = getrgb(tint)
    tl = getcolor(tint, "L")  # tint color's overall luminosity
    if not tl:
        tl = 1  # avoid division by zero
    tl = float(tl)  # compute luminosity preserving tint factors
    sr, sg, sb = map(lambda tv: tv / tl, (tr, tg, tb))  # per component
    # adjustments
    # create look-up tables to map luminosity to adjusted tint
    # (using floating-point math only to compute table)
    luts = (tuple(map(lambda lr: int(lr * sr + 0.5), range(256))) +
            tuple(map(lambda lg: int(lg * sg + 0.5), range(256))) +
            tuple(map(lambda lb: int(lb * sb + 0.5), range(256))))
    l = grayscale(src)  # 8-bit luminosity version of whole image
    if Image.getmodebands(src.mode) < 4:
        merge_args: tuple = (src.mode, (l, l, l)
                             )  # for RGB verion of grayscale
    else:  # include copy of src image's alpha layer
        a = Image.new("L", src.size)
        a.putdata(src.getdata(3))
        merge_args = (src.mode, (l, l, l, a))  # for RGBA verion of grayscale
        luts += tuple(range(256))  # for 1:1 mapping of copied alpha values

    image = Image.merge(*merge_args).point(luts)
    new_image = Image.new("RGBA", image.size,
                          "WHITE")  # Create a white rgba background
    new_image.paste(image, (0, 0), image)
    return new_image
Example #10
0
def image_tint(im, tint='#ff0000'):

    src = Image.new('RGB', im.size)
    src.paste(im)

    tr, tg, tb = getrgb(tint)
    tl = getcolor(tint, "L")  # tint color's overall luminosity
    if not tl: tl = 1  # avoid division by zero
    tl = float(tl)  # compute luminosity preserving tint factors
    sr, sg, sb = map(lambda tv: tv / tl,
                     (tr, tg, tb))  # per component adjustments

    # create look-up tables to map luminosity to adjusted tint
    # (using floating-point math only to compute table)
    luts = (list(map(lambda lr: int(lr * sr + 0.5), range(256))) +
            list(map(lambda lg: int(lg * sg + 0.5), range(256))) +
            list(map(lambda lb: int(lb * sb + 0.5), range(256))))
    l = grayscale(src)  # 8-bit luminosity version of whole image
    if Image.getmodebands(src.mode) < 4:
        merge_args = (src.mode, (l, l, l))  # for RGB verion of grayscale
    else:  # include copy of src image's alpha layer
        a = Image.new("L", src.size)
        a.putdata(src.getdata(3))
        merge_args = (src.mode, (l, l, l, a))  # for RGBA verion of grayscale
        luts += range(256)  # for 1:1 mapping of copied alpha values

    return Image.merge(*merge_args).point(luts)
Example #11
0
def image_tint(src,
               tint="#ffffff"):  # From https://stackoverflow.com/a/12310820
    if src.mode not in ["RGB", "RGBA"]:
        raise TypeError("Unsupported source image mode: {}".format(src.mode))
    src.load()

    tr, tg, tb = getrgb(tint)
    tl = getcolor(tint, "L")
    if not tl:
        tl = 1
    tl = float(tl)
    sr, sg, sb = map(lambda tv: tv / tl, (tr, tg, tb))
    luts = (tuple(map(lambda lr: int(lr * sr + 0.5), range(256))) +
            tuple(map(lambda lg: int(lg * sg + 0.5), range(256))) +
            tuple(map(lambda lb: int(lb * sb + 0.5), range(256))))
    l = grayscale(src)
    if Image.getmodebands(src.mode) < 4:
        merge_args = (src.mode, (l, l, l))
    else:
        a = Image.new("L", src.size)
        a.putdata(src.getdata(3))

        luts += tuple(range(256))

    return Image.merge(*merge_args).point(luts)
Example #12
0
def image_tint(src, tint='#ffffff'):
    if Image.isStringType(src):  # file path?
        src = Image.open(src)
    if src.mode not in ['RGB', 'RGBA']:
        raise TypeError('Unsupported source image mode: {}'.format(src.mode))
    src.load()

    tr, tg, tb = getrgb(tint)
    tl = getcolor(tint, "L")  # tint color's overall luminosity
    if not tl: tl = 1  # avoid division by zero
    tl = float(tl)  # compute luminosity preserving tint factors
    sr, sg, sb = map(lambda tv: tv/tl, (tr, tg, tb))  # per component
                                                      # adjustments
    # create look-up tables to map luminosity to adjusted tint
    # (using floating-point math only to compute table)
    luts = (tuple(map(lambda lr: int(lr*sr + 0.5), range(256))) +
            tuple(map(lambda lg: int(lg*sg + 0.5), range(256))) +
            tuple(map(lambda lb: int(lb*sb + 0.5), range(256))))
    l = grayscale(src)  # 8-bit luminosity version of whole image
    if Image.getmodebands(src.mode) < 4:
        merge_args = (src.mode, (l, l, l))  # for RGB verion of grayscale
    else:  # include copy of src image's alpha layer
        a = Image.new("L", src.size)
        a.putdata(src.getdata(3))
        merge_args = (src.mode, (l, l, l, a))  # for RGBA verion of grayscale
        luts += tuple(range(256))  # for 1:1 mapping of copied alpha values

    return Image.merge(*merge_args).point(luts)
Example #13
0
 def generate_png_stream(self, sizes, rotation=None, page_number=1, out_file=None):
     """
     Generate a PNG file for a given page.
     """
     # Skip pages before the desired one
     p = self.pages()
     while True:
         page = p.next()
         if page.page_number == page_number:
             break
     else:
         raise IndexError
     # Check if we must rotate
     if rotation is None:
         try:
             rotation = self.rotation_defaults[page_number]
         except AttributeError:
             pass
     # We have the page in the right format
     ni = page
     # Rotation?
     if rotation:
         ni = ni.rotate(self.DEGREES[rotation])
     # Scaling?
     if sizes:
         sizes["rotation"] = rotation
         ni = grayscale(ni).resize(page.util.newsize(sizes), Image.ANTIALIAS)
     # Save the resulting image
     ni.save(out_file, "PNG")
     del ni
Example #14
0
def tint_image(src, color="#FFFFFF"):
    """ Faster implementation of the above method """
    src.load()
    alpha = src.split()[3]  # r,g,b,alpha
    gray = grayscale(src)
    result = colorize(gray, (0, 0, 0, 0), color)
    result.putalpha(alpha)
    return result
def apply_filters(local_filename, blurred_image, grayscale_image):
    img = Image.open(local_filename)

    if blurred_image:
        img = img.filter(ImageFilter.GaussianBlur(50))

    if grayscale_image:
        img = grayscale(img)

    img.save(local_filename)
Example #16
0
def get_cropped_image(theme, x, y, grey = None): 
    '''crops a random image from a given theme.'''
    im_list = os.listdir('./images/%s' % theme)
    im_src = im_list[ randint(1,len(im_list)) - 1 ]
    im = Image.open("images/%s/%s" % (theme, im_src))
    out = im
    max_x, max_y = im.size
    if x < max_x or y < max_y: 
        out = fit(im, (x, y), Image.ANTIALIAS, 0, (.5, .5))
    if grey != None:
        out = grayscale(out)
    return out
Example #17
0
def kill(image: Image, *, gray: bool = True, x: bool = True, color = (255, 0, 0), width: int = 5) -> Image:
    i = image
    if gray:
        i = grayscale(i)
        rgbimg = Image.new("RGBA", i.size)
        rgbimg.paste(i)
        i = rgbimg
    if x:
        draw = ImageDraw.Draw(i)
        draw.line((0, 0) + i.size, fill = color, width = width)
        draw.line((0, i.size[1], i.size[0], 0), fill = color, width = width)
    return i
Example #18
0
 def process_image(self):
     file_path=self.get_path('*.*')
     print 'You selected', file_path 
     img=open(file_path)
     gray_img=grayscale(img)
     gray_pixels=gray_img.getdata() 
     new_img_pixels = self.make_cartoon_pic(gray_pixels, self.color_palette)
     img_new = new("RGB", img.size)
     img_new.putdata(new_img_pixels)
     img_new = self.make_dots(img_new, self.color_palette[2])
     img_new=self.make_lines(img_new, self.color_palette[0])
     
     import os 
     img_new.save(os.path.dirname(file_path) + "/" + "Nicole_cartoon.jpg") #saves image--change the last string to whatever you want your image saved as
Example #19
0
    def process_image(self):
        """
        changes an image to greyscale and calls functions to return an image with the new palette colors. Saves the
        new image and adds patterns to make it into a cartoon.
        """
        # debugging print statement:
        # print("Processing image...)
        gray_image = grayscale(self.image)  # change image to greyscale
        gray_pixels = gray_image.getdata(
        )  # get a list with the new greyscale colors for every pixel
        gray_image.save(
            "./img/grey_image_debug01.bmp")  # save new greyscale image

        # CHECKING PROGRESS
        # for i in range(10):
        #     print(gray_pixels[i]),

        # image = self.make_pattern(self.image, "FFFF00")
        # image.save("./img/pattern_test_debug02.bmp")

        # image = self.make_lines(self.image, "99FFFF")
        # image.save("./img/line_test_debug02.bmp")

        new_img_pixels = self.make_cartoon_pic(
            gray_pixels,
            self.color_palette)  # get a new list for pixel's colors
        # debugging print statement:
        # print("img total pixels:", self.w * self.h)
        # print("new_img total pixels:", len(new_img_pixels))
        assert (self.w * self.h == len(new_img_pixels))

        new_pixels = self.make_cartoon_pic(
            gray_pixels, self.color_palette)  # list pixels' new color palette
        new_image = new("RGB", self.image.size)  # create an empty image
        new_image.putdata(
            new_pixels)  # put new list of colors onto the new image
        new_image = self.make_pattern(
            new_image, self.color_palette[4],
            self.color_palette[3])  # add patterns to new image
        new_image = self.make_lines(
            new_image, self.color_palette[2],
            self.color_palette[0])  # add lines to new image
        new_image = self.diagonal_lines(
            new_image, self.color_palette[0],
            self.color_palette[2])  # add diagonal lines
        new_image.save("./img/new_image.bmp")  # save new image
Example #20
0
    def on_message(self, message):
        client_request = get_image_pb2.ClientRequest()
        client_request.ParseFromString(message)

        max_size_kwargs = {}
        if client_request.HasField('image_max_width'):
            if client_request.image_max_width <= 0:
                self._logger.error(
                    'Request error: image_max_width must be positive!')
                self.send_error()
                return
            max_size_kwargs['image_max_width'] = client_request.image_max_width

        if client_request.HasField('image_max_height'):
            if client_request.image_max_height <= 0:
                self._logger.error(
                    'Request error: image_max_height must be positive!')
                self.send_error()
                return
            max_size_kwargs[
                'image_max_height'] = client_request.image_max_height

        if client_request.image_generator == 'file':
            file_name = os.path.join(BASE_DIR, 'images/pic.jpg')
            image = gen_image_from_file(file_name, **max_size_kwargs)
        elif client_request.image_generator == 'PIL':
            image = gen_image_pil(**max_size_kwargs)
        else:
            self._logger.error('Request error: unknown image generator: %s',
                               client_request.image_generator)
            self.send_error()
            return

        if client_request.image_gray:
            image = grayscale(image)

        img_bytes_io = io.BytesIO()
        image.save(img_bytes_io, format='JPEG')
        image_byte = img_bytes_io.getvalue()

        server_response = get_image_pb2.ServerResponse()
        server_response.image_file_name = 'pic.jpg'
        server_response.image_byte = image_byte

        self.write_message(server_response.SerializeToString(), binary=True)
Example #21
0
    def cache_thumbnails(self):
        """
        Save a thumbnail for each page of this fax message. The size is
        hard-coded in the newsize() call.
        """
        p = self.pages()
        try:
            while True:
                i = p.next()
                ni = grayscale(i).resize(i.util.newsize(height=200), Image.ANTIALIAS)
                ni.save(settings.FAX_CACHE_NAME_FORMAT % (self.commid, i.page_number), "PNG")
                del ni
        except IndexError:
            pass

        def delete_thumbnails(self):
            for i in range(self.page_count()):
                os.unlink(settings.FAX_CACHE_NAME_FORMAT % (self.commid, i + 1))
    def process_image(self):
        """
        """
        img = open("./clown.bmp")  # !
        # print img.format, img.size, img.mode     # view image attributes
        gray_img = grayscale(img)
        gray_pixels = list(gray_img.getdata())
        gray_img.save("./" + "grey_img01.bmp")

        new_img_pixels = self.make_cartoon_pic(gray_pixels, self.color_palette)
        new_img = new("RGB", img.size)
        new_img.putdata(new_img_pixels)
        new_img = self.make_pattern(new_img, self.color_palette[2],
                                    (0, 255, 0))
        new_img = self.make_lines(new_img, self.color_palette[4],
                                  (0, 255, 255))
        new_img = self.make_rect(new_img, self.color_palette[1],
                                 (255, 255, 255))
        new_img.save("./" + "final_img.bmp")
Example #23
0
def post_image(file):
    """
    Given a posted image, classify it using the pretrained model.

    This will take 'any size' image, and scale it down to 28x28 like our MNIST
    training data -- and convert to grayscale.

    Parameters
    ----------
    file:
        Bytestring contents of the uploaded file. This will be in an image file format.
    """
    image = Image.open(io.BytesIO(file.read()))
    image = grayscale(fit(image, (28, 28)))
    image_bytes = image.tobytes()
    image_array = np.reshape(np.frombuffer(image_bytes, dtype=np.uint8),
                             (28, 28))
    print(image_array.shape)
    return json.dumps({'digit': None})
Example #24
0
def canny(image):
    imcopy = grayscale(image)
    imcopy1 = imcopy.filter(ImageFilter.GaussianBlur)
    imcopy2, gradients  = sobel(imcopy1)
    imcopy3 = nms(imcopy2, gradients)
    m = median(imcopy3)
    low = m*0.66
    high = m*1.33
    weakness = [[0 for i in range(image.size[1])] for j in range(image.size[0])]
    for i in range(image.size[0]):
        for j in range(image.size[1]):
            if imcopy3.getpixel((i,j)) < low:
                weakness[i][j]=0
                imcopy3.putpixel((i,j),0)
            elif imcopy3.getpixel((i,j)) < high:
                weakness[i][j]=1
            else:
                weakness[i][j]=2
    for i in range(image.size[0]):
        for j in range(image.size[1]):
            if weakness[i][j]==1:
                strong = False
                for i1 in range(-1,1):
                    for j1 in range(-1,1):
                        x = i+i1
                        x = x if x>0 else 0
                        x = x if x<image.size[0] else image.size[0]-1
                        y = j+j1
                        y = y if y>0 else 0
                        y = y if y<image.size[1] else image.size[1]-1
                        if weakness[x][y]==2:
                            strong = True
                            break
                        else:
                            imcopy3.putpixel((i,j),0)
                    if strong:
                        break
    return imcopy3
Example #25
0
def post_image(file):
    """
    Given a posted image, classify it using the pretrained model.

    This will take 'any size' image, and scale it down to 28x28 like our MNIST
    training data -- and convert to grayscale.

    Parameters
    ----------
    file:
        Bytestring contents of the uploaded file. This will be in an image file format.
    """
    #using Pillow -- python image processing -- to turn the poseted file into bytes
    image = Image.open(io.BytesIO(file.read()))
    image = grayscale(fit(image, (28, 28)))
    image_bytes = image.tobytes()
    #image needs to be a 'batch' though only of one, and with one channel -- grayscale
    image_array = np.reshape(np.frombuffer(image_bytes,  dtype=np.uint8), (1, 28, 28, 1))
    prediction = MNIST_MODEL.predict(image_array)
    #argmax to reverse the one hot encoding
    digit = np.argmax(prediction[0])
    #need to convert to int -- numpy.int64 isn't known to serialize
    return json.dumps({'digit': int(digit)})
Example #26
0
    def image_tint(image, tint='#ffffff'):
        """
        Function to merge two images without alpha

        Parameters:
        image (str): Path to the image
        tint (str): Hex code for the tint

        Returns:
        Image object for further use
        """
        image = image.convert('RGBA')
        image.load()

        tr, tg, tb = getrgb(tint)
        tl = getcolor(tint, "L")  # tint color's overall luminosity
        tl = 1 if not tl else tl  # avoid division by zero
        tl = float(tl)  # compute luminosity preserving tint factors
        sr, sg, sb = map(lambda tv: tv / tl, (tr, tg, tb))  # per component
        # adjustments
        # create look-up tables to map luminosity to adjusted tint
        # (using floating-point math only to compute table)
        luts = (tuple(map(lambda lr: int(lr * sr + 0.5), range(256))) +
                tuple(map(lambda lg: int(lg * sg + 0.5), range(256))) +
                tuple(map(lambda lb: int(lb * sb + 0.5), range(256))))
        lum = grayscale(image)  # 8-bit luminosity version of whole image
        if Image.getmodebands(image.mode) < 4:
            merge_args = (image.mode, (lum, lum, lum)
                          )  # for RGB verion of grayscale
        else:  # include copy of image image's alpha layer
            a = Image.new("L", image.size)
            a.putdata(image.getdata(3))
            merge_args = (image.mode, (lum, lum, lum, a)
                          )  # for RGBA verion of grayscale
            luts += tuple(range(256))  # for 1:1 mapping of copied alpha values

        return Image.merge(*merge_args).point(luts)
Example #27
0
 async def duotone(self,
                   ctx: aoi.AoiContext,
                   black: AoiColor,
                   white: AoiColor,
                   mid: Union[AoiColor, str] = None,
                   black_point: int = 0,
                   white_point: int = 255,
                   mid_point: int = 127):
     if isinstance(mid, str):
         if mid.lower() == "none":
             mid = None
         else:
             raise commands.BadArgument("mid must be a color or None")
     if not ctx.message.attachments or len(ctx.message.attachments) == 0:
         return await ctx.send_error(
             "I need an image! Attach it with your command as a file.")
     attachment: discord.Attachment = ctx.message.attachments[0]
     if not self._is_image(attachment.filename):
         return await ctx.send_error(
             "Invalid image type. Give me a jpg, jpeg, or png")
     buf = io.BytesIO()
     buf.seek(0)
     await ctx.trigger_typing()
     await attachment.save(buf)
     im: Image = Image.open(buf).convert("RGB")
     gs = grayscale(im)
     duo = colorize(gs, black.to_rgb(), white.to_rgb(),
                    mid.to_rgb() if mid else None, black_point, white_point,
                    mid_point)
     duo = Image.composite(duo,
                           Image.new("RGB", duo.size, (0x00, 0x00, 0x00)),
                           gs)
     buf.close()
     buf = io.BytesIO()
     duo.save(buf, "PNG")
     await ctx.embed(image=buf)
Example #28
0
def tintImage(img, tint):
	i = colorize(grayscale(img), (0,0,0), tint)
	i.putalpha(img.split()[3])
	return i
Example #29
0
def tintImage(img, tint):
    i = colorize(grayscale(img), (0, 0, 0), tint)
    i.putalpha(img.split()[3])
    return i
Example #30
0
# -*- coding: utf-8 -*-
"""
Created on Wed May 16 11:37:34 2018

@author: deepe
"""
from PIL import Image
from PIL.ImageOps import grayscale

image = Image.open('sample.jpg')
image = grayscale(image).rotate(90)
half_the_width = image.size[0] / 2
half_the_height = image.size[1] / 2
newimg = image.crop((half_the_width - 80, half_the_height - 102,
                     half_the_width + 80, half_the_height + 102))
newimg.thumbnail((75, 75))
newimg.show()

newimg.save("Image1.png")
Example #31
0
#rotate 90degree
new_img.rotate(90).save(img_name +".jpg")



#create thumbnail
new_img.thumbnail((75,75))
new_img.save(img_name +".jpg")


#crop image
print(new_img.size)


#new_img.crop((27,27,160,204)).save(img_name +".jpg")


ImageOps.fit(new_img,(160,204), centering=(0.5,0.5)).save(img_name +".jpg")


#greyscale

new_img.convert('L').save(img_name +".jpg")
#alternate way
from PIL.ImageOps import grayscale
grayscale(new_img).save(img_name +".jpg")

new_img.show()

Example #32
0
all_masks = glob.glob(os.path.join(folder, "Training400", "Annotation", "Disc_Cup_Masks", "Glaucoma") + "/*") + \
    glob.glob(os.path.join(folder, "Training400", "Annotation",
                           "Disc_Cup_Masks", "Non-Glaucoma") + "/*")

k = list(range(400))
random.shuffle(k)

ratio = 2

# Prepare training dataset
for i in k[:int(len(k) * train_test_ratio[0])]:
    filename = os.path.split(all_imgs[i])[-1]
    target_path = os.path.join(folder, "train", "img") + "/" + filename
    print(target_path)

    mask = grayscale(Image.open(all_masks[i]))
    mask = np.array(mask)
    mask = cv2.threshold(mask, 150, 255, cv2.THRESH_BINARY_INV)[1]
    mask = imresize(mask, (mask.shape[0] // 2, mask.shape[1] // 2))

    filename = os.path.split(all_masks[i])[-1]

    target_mask = os.path.join(folder, "train",
                               "masks" + "/") + filename[:-4] + ".png"
    cv2.imwrite(target_mask, mask)
    # shutil.copyfile(all_imgs[i], target_path)
    img = Image.open(all_imgs[i])
    img = np.array(img)
    img = imresize(img, (img.shape[0] // 2, img.shape[1] // 2, 3))
    cv2.imwrite(target_path, img[:, :, -1::-1])
Example #33
0

path = "C:\\Users\\hesko\\Desktop\\segmentation_training_data\\7_10002\\"
centers = open("train.csv", "w")
masks = glob.glob(path + "*.bmp")
masks = [mask for mask in masks if mask.find("gt") < 0 and mask.find("segmented") > 0 and mask.find("ground") < 0]
images = glob.glob(path + "*.jpg")
print(masks)
masks_cup = glob.glob(path + "*_ground_truth.bmp")

crop_size = 512

destination = "./refuge_cup_dataset/train/"
index = 0
for mask, img, cup in zip(masks, images, masks_cup):
    msk = np.array(grayscale(Image.open(mask)))
    msk = cv2.resize(msk, (1024, 1024))
    image = cv2.imread(img, cv2.IMREAD_COLOR)
    msk_cup =  cv2.threshold(np.array(grayscale(Image.open(cup))), 50, 255, cv2.THRESH_BINARY)[1]
    msk = cv2.threshold(msk, 100, 255, cv2.THRESH_BINARY)[1]
    x, y = center_of_mass(msk)
    img_name = os.path.split(img)[-1][:-4]
    x = int(x)
    y = int(y)

    if y < crop_size // 2:
        y = crop_size // 2
    centers.write(" ".join([img_name, str(x), str(y)])+ "\n")

    cv2.imwrite(destination + "masks/" + img_name + ".png", msk_cup[x-crop_size//2:x+crop_size//2, y-crop_size//2:y+crop_size//2])
    cv2.imwrite(destination + "img/" + img_name + ".jpg", image[x-crop_size // 2:x + crop_size // 2, y-crop_size//2:y+crop_size//2, :])
Example #34
0
imageList_2 = glob.glob(
    'C:\\Users\\Subham\\Documents\\EdgeDetectionVGG16\\Computed Image\\*.jpg')

True_Image_array = []
Computed_Image_array = []
'''
for image in imageList_1:
    img = cv2.imread(image)
    True_Image_array.append(img)

for image in imageList_2:
    img = cv2.imread(image)
    Computed_Image_array.append(img)
'''
cimg1 = Image.open(imageList_1[4])
gimg1 = grayscale(cimg1)
gimg1 = gimg1.resize((256, 256), resample=0)
gimg1.save('cropped.jpg')
timg = np.asarray(gimg1)

cimg2 = Image.open(imageList_2[4])
gimg2 = grayscale(cimg2)
gimg2.save('computed.jpg')
img = np.asarray(gimg2)
'''
True_Image_np_array = np.array(True_Image_array[0])
Computed_Image_np_array = np.array(Computed_Image_array[0])

print (True_Image_np_array.shape)
'''
w, h = gimg2.size
Example #35
0
all_imgs = glob.glob(os.path.join(folder, "Training400", "Glaucoma") + "/*") + \
    glob.glob(os.path.join(folder, "Training400", "Non-Glaucoma") + "/*")

all_masks = glob.glob(os.path.join(folder, "Training400", "Annotation", "Disc_Cup_Masks", "Glaucoma") + "/*") + \
    glob.glob(os.path.join(folder, "Training400", "Annotation",
                           "Disc_Cup_Masks", "Non-Glaucoma") + "/*")


cup_to_disc_ratio_g = []
cup_to_disc_ratio_n = []

numbers = np.zeros(2)

for msk in all_masks:
	img = np.array(grayscale(Image.open(msk)))

	cup = np.sum(img < 10)
	disc = np.sum(img < 150)

	if os.path.split(msk)[-1][0] == "g":
		print("Glaucomatic {}".format(cup/disc))
		cup_to_disc_ratio_g.append(cup / disc)
		numbers[1] += 1
	else:
		cup_to_disc_ratio_n.append(cup / disc)
		print("Non-glaucomatic {}".format(cup/disc))
		numbers[0] += 1

print("Glaucomatic c/d ratio {}".format(np.mean(cup_to_disc_ratio_g)/ numbers[1]))
print("Non-Glaucomatic c/d ratio {}".format(np.mean(cup_to_disc_ratio_n)/ numbers[0]))
from PIL import Image, ImageChops, ImageMath
from PIL import ImageOps
from PIL.ImageOps import grayscale
from PIL.ImageOps import colorize

right = Image.open('stereoimage/leftstereoimg.jpg')
left = Image.open('stereoimage/rightstereoimg.jpg')

width, height = right.size
rightMap = right.load()
leftMap = left.load()

right = grayscale(right)
right = colorize(right, (0, 0, 0), (0, 255, 255))  #cyan (0,255,255)
#right = colorize(right, (0,0,0),(0,0,255)) #blue (0,0,255)

left = grayscale(left)
left = colorize(left, (0, 0, 0), (255, 0, 0))  #red (255,0,0)
'''
#This code for blend
o = ImageChops.add(right,left,2)

o.save("3Dpics/anaglyph.jpg", "JPEG")
'''

#This code for additive blending
list_out = []
list_out1 = []
list_out2 = []
for red, cyan in itertools.izip(list(left.getdata()), list(right.getdata())):
    list_out.append(min(red[0], 255))