Example #1
0
def cache(im1: Image, im2: Image, mot_cle, cryptede, num_image,
          image_total) -> None:
    global et_4
    global et_5
    nb_tour = 1
    (largeur1, hauteur1) = (im1.width, im1.height)
    total = largeur1 * hauteur1
    pour22 = 1 / image_total
    for i in range(hauteur1):
        for e in range(largeur1):
            try:
                triplet1 = list(im1.getpixel((e, i)))
            except TypeError:
                triplet1 = im1.getpixel((e, i))
                triplet1 = [triplet1, triplet1, triplet1]
            tripletbi1 = crypte(triplet1, nb_tour, mot_cle, cryptede)
            im2.putpixel((e, i), tripletbi1)

            pour11 = nb_tour / total * 100
            pour1 = str(int(pour11)) + "%" + " " + "(" + str(
                nb_tour) + "/" + str(total) + ")"
            et_4.config(text=pour1)

            pour23 = pour11 * pour22
            if num_image >= 1:
                pour21 = pour22 * 100 + pour23
            else:
                pour21 = pour23
            pour2 = str(int(pour21)) + "%" + " " + "(" + str(
                num_image) + "/" + str(image_total) + ")"
            et_5.config(text=pour2)

            nb_tour += 1
    et_4.config(text=pour1)
Example #2
0
 def _extract_ticks_on_vertical_axis(self, image: Image, left_line_x: int) -> list:
     ticks = []
     for y in range(image.size[1]):
         if image.getpixel((left_line_x - 1, y)) == image.getpixel((left_line_x - 2, y)) \
                 == self.LEFT_BOTTOM_LINE_COLOR:
             ticks.append(y)
     return ticks
Example #3
0
    def _extract_vertical_lines(self, image: Image) -> tuple:
        left_x = right_x = 0
        best_left = best_right = 0

        for x in range(int(image.size[0] / 2)):
            v_sum_left = 0
            for y in range(image.size[1]):
                if image.getpixel((x, y)) == self.LEFT_BOTTOM_LINE_COLOR:
                    v_sum_left += 1
            if v_sum_left > best_left:
                best_left = v_sum_left
                left_x = x
            if best_left > image.size[1] / 2:  # optimization
                break

        for x in range(image.size[0] - 1, int(image.size[0] / 2), -1):
            v_sum_right = 0
            for y in range(image.size[1]):
                if image.getpixel((x, y)) == self.RIGHT_TOP_LINE_COLOR:
                    v_sum_right += 1
            if v_sum_right > best_right:
                best_right = v_sum_right
                right_x = x
            if best_right > image.size[1] / 2:  # optimization
                break

        return left_x, right_x
Example #4
0
def cache(im1:Image, im2:Image, mot_cle, cryptede, num_image, image_total)->None:
	global et_4
	global et_5
	nb_tour = 1
	(largeur1, hauteur1) = (im1.width, im1.height)
	total = largeur1 * hauteur1
	pour22 = 1 / image_total
	for i in range(hauteur1):
		for e in range(largeur1):
			try:
				triplet1 = list(im1.getpixel((e, i)))
			except TypeError:
				triplet1 = im1.getpixel((e, i))
				triplet1 = [triplet1, triplet1, triplet1]
			tripletbi1 = crypte(triplet1, nb_tour, mot_cle, cryptede)
			im2.putpixel((e, i), tripletbi1)

			pour11 = nb_tour / total * 100
			pour1 = str(int(pour11)) + "%" + " " + "("+str(nb_tour)+"/"+str(total)+")"
			et_4.config(text=pour1)

			pour23 = pour11 * pour22
			if num_image >= 1:
				pour21 = pour22*100 + pour23
			else:
				pour21 = pour23
			pour2 = str(int(pour21)) + "%" + " " + "("+str(num_image)+"/"+str(image_total)+")"
			et_5.config(text=pour2)

			nb_tour += 1
	et_4.config(text=pour1)
Example #5
0
 def _extract_ticks_on_horizontal_axis(self, image: Image, bottom_line_y: int) -> list:
     ticks = []
     for x in range(image.size[0]):
         if image.getpixel((x, bottom_line_y + 1)) == image.getpixel((x, bottom_line_y + 2)) \
                 == self.LEFT_BOTTOM_LINE_COLOR:
             ticks.append(x)
     return ticks
    def fade(a: Image, b: Image, frames: int):
        """
        Create fading transition from first image to second.
        Resulting animation will take specified amount of frames (not really accurate)

        :param a: First image
        :param b: Second Image
        :param frames: Number of frames
        :return: List of images - resulting animation
        """

        # we only need to change pixels with different colors
        different_pixels = []
        for x in range(32):
            for y in range(32):
                if a.getpixel((x, y)) != b.getpixel((x, y)):
                    different_pixels.append((x, y))

        # we will change them in random order
        random.shuffle(different_pixels)
        im = a.copy()
        ret = [a.copy()]
        for i in range(frames - 1):
            # Each frame we will change equal amount of pixels
            to_take = len(different_pixels) // (frames - 1)
            # last frame is special case - since to_take was rounded down, there will be more pixels
            # so we change all remaining pixels
            to_process = different_pixels[
                i * to_take:(i + 1) *
                to_take] if i != frames - 1 else different_pixels[i * to_take:]
            for pos in to_process:
                im.putpixel(pos, b.getpixel(pos))
            ret.append(im.copy())
        ret.append(b.copy())
        return ret
Example #7
0
    def _extract_horizontal_lines(self, image: Image) -> tuple:
        top_y = bottom_y = 0
        best_top = best_bottom = 0

        for y in range(int(image.size[1] / 2)):
            h_sum_t = 0
            for x in range(image.size[0]):
                if image.getpixel((x, y)) == self.RIGHT_TOP_LINE_COLOR:
                    h_sum_t += 1
            if h_sum_t > best_top:
                best_top = h_sum_t
                top_y = y
            if best_top > image.size[0] / 2:  # optimization
                break

        for y in range(image.size[1] - 1, int(image.size[1] / 2), -1):
            h_sum_b = 0
            for x in range(image.size[0]):
                if image.getpixel((x, y)) == self.LEFT_BOTTOM_LINE_COLOR:
                    h_sum_b += 1
            if h_sum_b > best_bottom:
                best_bottom = h_sum_b
                bottom_y = y
            if best_bottom > image.size[0] / 2:  # optimization
                break

        return top_y, bottom_y
Example #8
0
 def around(img: Image, x, y, val_x, val_y):
     """Gets the rgb values averages for all px in radius X around the given px"""
     colors = []
     r_color = []
     max_x, max_y = img.height, img.width
     for i, j in zip(
             range(val_x),
             range(val_y)):  # Get the rgb values of all the pixels around
         try:
             colors.append(img.getpixel((x + i, y + j)))
             colors.append(img.getpixel((x - i, y - j)))
             colors.append(img.getpixel((x - i, y + j)))
             colors.append(img.getpixel((x + i, y - j)))
         except IndexError:
             if x + i > max_x:
                 x = max_x
             if y + j > max_y:
                 y = max_y
             print("IndexError handled ! X & Y are now ", x, y,
                   " as the permitted max image value")
             colors.append(img.getpixel((x, y)))
     for i in range(3):  # Compute the average for each rbg value
         t_color = [x[i] for x in colors]
         r_color.append(sum(t_color) // len(colors))
     return r_color
Example #9
0
def trim_image(im: Image):
    prev, cur = (), ImageChops.difference(
        im, Image.new(im.mode, im.size, im.getpixel((0, 0)))).getbbox()
    while prev != cur:
        im = im.crop(cur)
        prev, cur = cur, ImageChops.difference(
            im, Image.new(im.mode, im.size, im.getpixel((0, 0)))).getbbox()
    return ImageOps.expand(im, border=20, fill=BACKGROUND)
Example #10
0
def _get_pixels(im: Image, x: int, y: int,
                size: int) -> Tuple[int, int, int, int]:
    nw_value = im.getpixel((x, y))
    ne_value = im.getpixel((x + size, y))
    se_value = im.getpixel((x + size, y + size))
    sw_value = im.getpixel((x, y + size))

    return nw_value, ne_value, se_value, sw_value
Example #11
0
def get_transparency(image: Image):
    width, height = image.size
    border = ([image.getpixel((0, j)) for j in range(height)] +
              [image.getpixel((width - 1, j)) for j in range(height)] +
              [image.getpixel((i, 0)) for i in range(width)] +
              [image.getpixel((i, height - 1)) for i in range(width)])
    transparency = Counter(border).most_common(1)[0][0]
    return transparency
Example #12
0
def restore_image(image: Image):
    for i in range(image.size[0]):
        for j in range(image.size[1]):
            r = image.getpixel((i, j))[0]
            g = image.getpixel((i, j))[1]
            b = image.getpixel((i, j))[2]
            if r_left_border <= r <= r_right_border and g_left_border <= g <= g_right_border \
                    and b_left_border <= b <= b_right_border:  # От 170 до 223 для всех
                image.putpixel((i, j), (r_fill, g_fill, b_fill))  # r, g и b равны 255
Example #13
0
def seed_region_growth(im: Image, se: (int, int), th: int):
    def in_threshold(se: (int, int, int, int), cu: (int, int, int, int), th):
        return (se[0] - th <= cu[0] and cu[0] <= se[0] + th) \
            and (se[1] - th <= cu[1] and cu[1] <= se[1] + th) \
            and (se[2] - th <= cu[2] and cu[2] <= se[2] + th)

    co = [[False for y in range(im.size[1])] for x in range(im.size[0])]

    st = [se]
    cu = se
    while len(st) > 0:
        co[cu[0]][cu[1]] = True

        found = False
        ne = (cu[0], cu[1] + 1)
        if 0 <= ne[0] and ne[0] < im.size[0] and 0 <= ne[1] and ne[
                1] < im.size[1]:
            if in_threshold(im.getpixel(se), im.getpixel(ne),
                            th) and co[ne[0]][ne[1]] == False:
                found = True

        if not found:
            ne = (cu[0] + 1, cu[1])
            if 0 <= ne[0] and ne[0] < im.size[0] and 0 <= ne[1] and ne[
                    1] < im.size[1]:
                if in_threshold(im.getpixel(se), im.getpixel(ne),
                                th) and co[ne[0]][ne[1]] == False:
                    found = True

        if not found:
            ne = (cu[0], cu[1] - 1)
            if 0 <= ne[0] and ne[0] < im.size[0] and 0 <= ne[1] and ne[
                    1] < im.size[1]:
                if in_threshold(im.getpixel(se), im.getpixel(ne),
                                th) and co[ne[0]][ne[1]] == False:
                    found = True

        if not found:
            ne = (cu[0] - 1, cu[1])
            if 0 <= ne[0] and ne[0] < im.size[0] and 0 <= ne[1] and ne[
                    1] < im.size[1]:
                if in_threshold(im.getpixel(se), im.getpixel(ne),
                                th) and co[ne[0]][ne[1]] == False:
                    found = True

        if not found:
            cu = st.pop()
        else:
            st.append(cu)
            cu = ne

    for x in range(im.size[0]):
        for y in range(im.size[1]):
            im_pe = im.getpixel((x, y))
            re_pe = (255, 255, 255)
            if co[x][y]:
                re_pe = im_pe
            im.putpixel((x, y), re_pe)
    return im, None
Example #14
0
def merge(img1: Image, img2: Image) -> Image:
    width, height = img1.size
    for w in range(0, width):
        for h in range(0, height):
            r1, g1, b1 = img1.getpixel((w, h))
            r2, g2, b2, a2 = img2.getpixel((w, h))
            if filter1(r1, g1, b1, 0) < filter1(r2, b2, g2, 0.8):
                # img1.putpixel((w,h),(r2,g2,b2,0))
                img1.putpixel((w, h),
                              (((width - w) // width * r1 + r2) // 2,
                               ((width - w) // width * g1 + g2) // 2,
                               ((width - w) // width * b1 + b2) // 2, 0))
    return img1
Example #15
0
def getBoard(img: Image):
    board = [[], [], [], [], [], []]
    for i in range(6):
        for j in range(7):
            coordX = (50 + (115 * j))
            coordY = (50 + (115 * i))
            if tuple(img.getpixel((coordX, coordY))) == tuple((255, 255, 255)):
                board[i].append(0)
            elif tuple(img.getpixel((coordX, coordY))) == tuple((255, 0, 0)):
                board[i].append(2)
            else:
                board[i].append(1)
    return board
Example #16
0
def imgFilter(img: Image,
              radius: int = 100,
              center: tuple = None,
              mouse: tuple = None,
              antialias=2):
    width, height = img.size
    new_img = img.copy()
    r = radius

    if center is None:
        center = (130, 120)
    if mouse is None:
        mouse = (130, 50)

    cx, cy = center
    mx, my = mouse

    nband = len(img.getpixel((0, 0)))
    antialias = antialias

    for x in range(width):
        for y in range(height):
            if sqrt((x - cx)**2 + (y - cy)**2) > r:
                continue

            found = 0
            psum = (0, ) * nband

            # anti-alias
            for ai in range(antialias):
                _x = x + ai / float(antialias)
                for aj in range(antialias):
                    _y = y + aj / float(antialias)

                    u, v = warp(_x, _y, r, (cx, cy), (mx, my))
                    u = int(round(u))
                    v = int(round(v))
                    if not (0 <= u < width and 0 <= v < height):
                        continue
                    pt = img.getpixel((u, v))
                    psum = map(operator.add, psum, pt)
                    found += 1

            if found > 0:
                # print((found, ) * len(list(psum)))
                psum = _div(list(psum), found)
                # print(psum)
                # psum = map(operator.truediv, list(psum), (found, ) * len(list(psum)))
                new_img.putpixel((x, y), tuple(psum))

    return new_img
Example #17
0
def top_down_noise(im: Image, size: int, randomization: int = 30):
    value_origin = random.randint(1, 255)
    im.putpixel((0, 0), value_origin)

    for _x in range(1, size):
        left = im.getpixel((_x - 1, 0))
        value = max(
            1, min(255, left + random.randint(-randomization, randomization)))
        im.putpixel((_x, 0), value)

    for _y in range(1, size):
        avrg = (im.getpixel((0, _y - 1)) + im.getpixel((1, _y - 1))) // 2
        im.putpixel(
            (0, _y),
            max(1,
                min(255,
                    avrg + random.randint(-randomization, randomization))))
        for _x in range(1, size - 1):
            avrg = (im.getpixel((_x - 1, _y - 1)) + im.getpixel(
                (_x, _y - 1)) + im.getpixel((_x + 1, _y - 1))) // 3
            im.putpixel(
                (_x, _y),
                max(
                    1,
                    min(255,
                        avrg + random.randint(-randomization, randomization))))
        avrg = (im.getpixel((size - 2, _y)) + im.getpixel((size - 1, _y))) // 2
        im.putpixel(
            (size - 1, _y),
            max(1,
                min(255,
                    avrg + random.randint(-randomization, randomization))))
Example #18
0
def get_neighbors(image: Image, x: int, y: int) -> Sequence[int]:
    width, height = image.size

    neighbors = []
    if 0 < x:
        neighbors.append(image.getpixel((x - 1, y)))
    if x < width - 1:
        neighbors.append(image.getpixel((x + 1, y)))
    if 0 < y:
        neighbors.append(image.getpixel((x, y - 1)))
    if y < height - 1:
        neighbors.append(image.getpixel((x, y + 1)))

    return neighbors
Example #19
0
    def get_distance(bg_image: Image, fullbg_image: Image):
        # 阈值
        threshold = 200

        for i in range(60, bg_image.size[0]):
            for j in range(bg_image.size[1]):
                bg_pix = bg_image.getpixel((i, j))
                fullbg_pix = fullbg_image.getpixel((i, j))
                r = abs(bg_pix[0] - fullbg_pix[0])
                g = abs(bg_pix[1] - fullbg_pix[1])
                b = abs(bg_pix[2] - fullbg_pix[2])

                if r + g + b > threshold:
                    return i
Example #20
0
def get_border_threshold(image: Image) -> set:
    """获取图片边框的像素(灰度)值"""
    thresholds = set()
    width, height = image.size
    for x in range(width):
        pixel_start = image.getpixel((x, 0))
        pixel_end = image.getpixel((x, height - 1))
        thresholds.add(pixel_start)
        thresholds.add(pixel_end)
    for y in range(height):
        pixel_start = image.getpixel((0, y))
        pixel_end = image.getpixel((width - 1, y))
        thresholds.add(pixel_start)
        thresholds.add(pixel_end)
    return thresholds
Example #21
0
def paint_polygon(polygon: tr.Triangle, draw: ImageDraw, texture: Image, z_buffer ):
    """
    Colorize inner part of triangle with specified color
    """
    first , second , third = polygon.first.projection() , polygon.second.projection() , polygon.third.projection()

    x0 = int(min(first.x, second.x, third.x))
    x1 = int(max(first.x, second.x, third.x))
    y0 = int(min(first.y, second.y, third.y))
    y1 = int(max(first.y, second.y, third.y))

    for x in range( x0 , x1 + 1 ) :
        for y in range( y0 , y1 + 1 ) :
            barycentric = polygon.getBaricenterCordinates(gr.Point(x, y))

            is_inside_triangle = all( i >= 0 for i in barycentric )
            if is_inside_triangle :
                # получаем координаты пикселя, соответствующего отрисовываемому в данный момент, из файла текстур
                # получаем цвет пикселя из файла текстур по вычисленным координатам
                z = polygon.tmp_Z(barycentric)
                get_pixel = get_texture_point(polygon, barycentric)
                color = (texture.getpixel(get_pixel))
                pixels = texture.load()

                intensity = (polygon.normalFirst.first +polygon.normalFirst.second + polygon.normalFirst.third) *barycentric[0]+\
                    (polygon.normalSecond.first +polygon.normalSecond.second + polygon.normalSecond.third) *barycentric[1]+\
                    (polygon.normalThird.first +polygon.normalThird.second + polygon.normalThird.third) *barycentric[2]

                color = (int(color[0]*intensity),int(color[1]*intensity),int(color[2]*intensity))
                draw_pixel(tr.Point(x, y, z), z_buffer, draw,get_pixel,intensity ,pixels,color)
Example #22
0
def create_mask(
    source: Image, mask: Tuple[int, int, int] = (0, 1, 2)) -> Image:
    """Create an image mask for pasting purposes.

    Args:
        source: Image to create the mask from
        mask:   Tuple containing colormap indices to be masked

                Default values are equivalent to white, black, and red
                for an inky display

    Returns:
        An image mask for the source image

    Attribution:
        This method was written by the folks at pimoroni, and can be found within
        their examples for their inky displays.

    """
    mask_image = Image.new("1", source.size)
    w, h = source.size
    for x in range(w):
        for y in range(h):
            p = source.getpixel((x, y))
            if p in mask:
                mask_image.putpixel((x, y), 255)
    return mask_image
Example #23
0
def _image_to_packed_buffer(im: Image, palette: Dict,
                            bits_per_pixel: int) -> bytes:
    width, height = im.size

    current_byte = 0
    current_bit = 0
    image_data = []

    # Row first
    for row in range(height):
        for col in range(width):
            # Return an index in the indexed colors list for indexed address spaces
            # left to right
            # Perform implicit rotation here (0,0) is left top in BAGL, and generally left bottom for various canvas
            color_index = im.getpixel((col, row))

            # Remap index by luminance
            color_index = palette[color_index]

            # le encoded
            current_byte += color_index << current_bit
            current_bit += bits_per_pixel

            if current_bit >= 8:
                image_data.append(current_byte & 0xFF)
                current_bit = 0
                current_byte = 0

        # Handle last byte if any
    if current_bit > 0:
        image_data.append(current_byte & 0xFF)
    return bytes(image_data)
Example #24
0
    def fill_image(self, key_index, image: Image) -> None:
        """
        If you want to draw the image in memory, or have it loaded before using Pillow you can use this method to show
        it on the given key.
        """
        Infinitton.check_valid_key_index(key_index)

        if image.width != ICON_SIZE or image.height != ICON_SIZE:
            image = image.resize((ICON_SIZE, ICON_SIZE))

        image = image.transpose(Image.FLIP_TOP_BOTTOM)

        data = bytearray()
        for r in range(ICON_SIZE):
            row_data = bytearray(ICON_SIZE * 3)

            for c in range(ICON_SIZE):
                pixel = image.getpixel((r, c))
                pixel_data_start = 3 * c

                row_data[pixel_data_start] = pixel[0]
                row_data[pixel_data_start + 1] = pixel[1]
                row_data[pixel_data_start + 2] = pixel[2]

            row_data.reverse()
            data += row_data
        self._send_image(key_index, data)
Example #25
0
def encode_image_preview(input: Image):
    output = bytes()
    prev = -1
    count = 0
    c = 0
    def flush():
        nonlocal count, output, prev
        if count > 1: prev |= 0x0020
        output += struct.pack("H", prev)
        if count > 1: output += struct.pack("BB", (count - 1) & 0xFF, (count - 1) >> 8)
        count = 0

    for y in range(input.height):
        for x in range(input.width):
            r, g, b, _ = input.getpixel((x, y))
            c = (r >> 3 << 11) | (g >> 3 << 6) | (b >> 3)
            if (prev == c and count < 4096) or prev == -1:
                count += 1
                prev = c
            else:
                flush()
                count = 1
                prev = c

    flush()
    return output
Example #26
0
def do(original_image: Image, degree):
    size = (original_image.size[0], original_image.size[1])
    if degree == 90 or degree == 270:
        size = (original_image.size[1], original_image.size[0])
    resulted_image = Image.new(mode=original_image.mode,
                               size=size,
                               color=(256, 256, 256))

    for x in range(original_image.size[0]):
        for y in range(original_image.size[1]):
            xy_res = (x, y)
            xy_ori = (x, y)
            if degree == 90:
                xy_res = (original_image.size[1] - y - 1, x)
                xy_ori = (x, y)
            elif degree == 180:
                xy_res = (x, original_image.size[1] - y - 1)
                xy_ori = (x, y)
            elif degree == 270:
                xy_res = (y, original_image.size[0] - x - 1)
                xy_ori = (x, y)

            resulted_image.putpixel(xy=xy_res,
                                    value=original_image.getpixel(xy_ori))

            # dest_buffer [ c ] [ m - r - 1 ] = source_buffer [ r ] [ c ];

    return resulted_image, None
Example #27
0
def boost_color(im: Image, color: (int, int, int)):
    factor = tuple(i / j for i, j in zip(color, mean_img_rgb(im)))
    for i in range(im.width):
        for j in range(im.height):
            rgb = im.getpixel((i, j))
            im.putpixel((i, j), tuple(map(lambda x: int(x[0] * x[1]), zip(rgb, factor))))
    return im
Example #28
0
    def process(im: Image, light_color: (int, int, int, int), dark_color: (int, int, int, int), contrast: float = 0.5):
        im = im.convert('RGB')
        out = Image.new(im.mode, im.size)
        out_pixels = out.load()

        do_calc_contrast = contrast != 0.5
        contrast_norm = (1 + contrast - 0.5)

        for i in range(im.size[0]):
            for j in range(im.size[1]):
                r, g, b = im.getpixel((i, j))

                if do_calc_contrast:
                    r = Duotone.__safe_color_value((r / 255.0 - 0.5) * contrast_norm + 0.5)
                    g = Duotone.__safe_color_value((g / 255.0 - 0.5) * contrast_norm + 0.5)
                    b = Duotone.__safe_color_value((b / 255.0 - 0.5) * contrast_norm + 0.5)
                average = math.floor(0.299 * r + 0.587 * g + 0.114 * b)
                h, s, l = Duotone.__rgb_to_hls(average, average, average)
                luminosity = max(0, min(254, math.floor(l * 254)))
                ratio = luminosity / 255.0
                new_r = math.floor(light_color[0] * ratio + dark_color[0] * (1 - ratio))
                new_g = math.floor(light_color[1] * ratio + dark_color[1] * (1 - ratio))
                new_b = math.floor(light_color[2] * ratio + dark_color[2] * (1 - ratio))
                out_pixels[i, j] = (new_r, new_g, new_b)
        return out
Example #29
0
def img2string(image: Image):
    width = 100
    height = 100
    ascii_char = list(
        "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcv2unxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
    )

    # 将256灰度映射到70个字符上
    def get_char(r, g, b, alpha=256):
        if alpha == 0:
            return ' '
        length = len(ascii_char)
        gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)

        unit = (256.0 + 1) / length
        return ascii_char[int(gray / unit)]

    image = image.resize((width, height))

    txt = ''

    # 将图片看成由像素点组成的二维数组,i代表每一行,j代表每一列
    for i in range(height):
        for j in range(width):
            # getpixel()函数的参数是由每个像素点在图片中的相对位置(w,h)组成的元组
            # 返回值是一个代表图片像素值的(r,g,b,alpha)元组
            txt += get_char(*image.getpixel((j, i)))
        txt += '\n'

    print(txt)
Example #30
0
def decode_from_image(im: Image, rows=5, cols=5, levels=(0x7f, 0xff)):
    '''返回:tid'''

    im.thumbnail((rows, cols), Image.BICUBIC)

    im_w, im_h = im.size

    n_level_bits = int(math.log2(len(levels)))
    total_bits = rows * cols * n_level_bits * 3
    unpacked_bits = [None] * total_bits

    code_image_properties_check(n_level_bits, total_bits)

    for i in range(cols):
        for j in range(rows):
            block_center = (i, j)
            px = im.getpixel(block_center)
            for k in range(3):
                level = min(levels, key=lambda x: abs(x - px[k]))
                bits = levels.index(level)
                for l in range(n_level_bits):
                    bit = (bits >> l) & 1
                    unpacked_bits[i + j * cols + l * total_bits //
                                  (3 * n_level_bits) +
                                  k * total_bits // 3] = bool(bit)
    unpacked_bits = unpacked_bits[:64]
    return decode(unpacked_bits)
Example #31
0
def get_pixels_from_line(line, im: Image):
    def _coords(z):
        x = im.width / 2 + round(z.real)
        y = im.height / 2 + round(z.imag)
        return x, y

    return [im.getpixel(_coords(z)) for z in line]
Example #32
0
def do(original_image: Image):
    freq = [
        [0 for x in range(256)],
        [0 for x in range(256)],
        [0 for x in range(256)],
    ]

    for x in range(original_image.size[0]):
        for y in range(original_image.size[1]):
            px = original_image.getpixel((x, y))
            freq[0][px[0]] += 1
            freq[1][px[1]] += 1
            freq[2][px[2]] += 1

    figure, axarr = plt.subplots(3)
    colors = ('red', 'green', 'blue')
    data = (freq[0], freq[1], freq[2])

    subplots = range(3)
    bands_range = range(256)
    for data, i, color in zip(data, subplots, colors):
        axarr[i].bar(bands_range, data, width=2, facecolor=color)
        axarr[i].set_xlim((0, 255))

    figure.subplots_adjust(hspace=0.3)

    return plt, None
Example #33
0
def proccessSquare(square: Image):
    square = square.convert('RGB')
    control = lambda x, y: square.getpixel((x, y)) == (33, 33, 33)
    def controlmany(*args):
        for (x, y) in args:
            if control(x, y) == False:
                return False
        return True

    if controlmany((44, 37), (52, 34), (61, 30), (59, 56), (59, 80)):
        return 1
    if controlmany((41, 40), (54, 30), (68, 41), (57, 62), (42, 81), (72, 81)):
        return 2
    if controlmany((41, 39), (54, 29), (69, 41), (56, 54), (69, 67), (55, 80), (40, 71)) and not control(44, 48):
        return 3
    if controlmany((64, 30), (50, 47), (39, 66), (65, 66), (65, 78), (71, 67)):
        return 4
    if controlmany((70, 30), (48, 29), (47, 52), (59, 49), (72, 64), (58, 80), (44, 71)):
        return 5
    if controlmany((63, 30), (48, 37), (43, 55), (58, 80), (71, 65), (59, 49)):
        return 6
    if controlmany((41, 31), (72, 30), (63, 54), (50, 80)):
        return 7
    if controlmany((55, 29), (57, 53), (57, 81), (42, 67), (71, 68), (44, 41), (71, 42)):
        return 8
    if controlmany((53, 30), (40, 46), (68, 45), (54, 62), (65, 72), (49, 80)):
        return 9
    return 0
Example #34
0
def print_pixels(image: Image) -> None:
    """Prints out the pixels, displaying a cut-out with a 1,
    a non-cut-out with 0."""
    for y_coord in range(image.height):
        for x_coord in range(image.width):
            print(int(image.getpixel((x_coord, y_coord)) == 255), end=" ")
        print()
Example #35
0
def check_black(file: Image, xy):
    x, _ = xy
    lst = [32, 83, 225, 106, 117, 38]  # 处于黑色坐标的y轴位置
    for y in lst:
        r1, g1, b1, a1 = file.getpixel((x, y))
        if (r1, g1, b1) == black:
            return True
    return False
Example #36
0
    def test_OpenCVToPIL(self):
        pil = self.im.asPIL().resize((180,120))
        im = Image(pil)
        cv = im.asOpenCV()
        pil = Image(cv).asPIL()

        for i in range(im.width):
            for j in range(im.height):
                for c in range(3):
                    self.assertAlmostEqual(pil.getpixel((i,j))[c],ord(cv.tostring()[i*3+j*im.width*3+2-c]))
Example #37
0
def image_hcl(Image):
    r = g = b = 0.0
    numpix = Image.width * Image.height

    for y in range(Image.height):
        for x in range(Image.width):
            pixel = Image.getpixel((x,y))
            r += pixel[0]
            g += pixel[1]
            b += pixel[2]
    avg_rgb = (r/numpix, g/numpix, b/numpix)
    return colourx.rgb_to_hcl(avg_rgb)
def reshape_img(img: Image):
    img_data = np.array(img.getdata()).reshape(img.size[1], img.size[0], 3)
    difference_found = False
    for i in range(img.size[0]):
        for j in range(img.size[1]):
            get_pixel = img.getpixel((i, j))
            data = img_data[j, i]

            if any(get_pixel != data):
                difference_found = True
                msg = 'Difference in pixel {pixel}: img.getpixel={getpixel}, ' \
                      'img_data={data}'.format(pixel=(i, j), getpixel=get_pixel, data=data)
                print(msg)
    if not difference_found:
        msg = 'The two images are identical'
        print(msg)
Example #39
0
def bgColor (source: Image, w: int, h: int, br: int) -> (int, int, int):
    for i in range(0, w):
        for j in range(0, h):
            yield tuple(map((lambda x: abs(x-br) if x > br else 0), list(source.getpixel((i, j)))))
Example #40
0
def fontColor (source: Image, w: int, h: int) -> ((int, int, int), int):
    for i in range(0, w):
        for j in range(0, h):
            pxColor = source.getpixel((i, j))
            yield (pxColor, (reduce(lambda x, y: x+y, pxColor) // 3 * (charset.total - 1)) // 255)