def makeMosaic(self): print "Making mosaic" if not self.finalimages: if self.load: self.loadData() elif self.hmode: self.selectTilesHMode() else: self.selectTiles() if len(self.finalimages) == 0: return if not self.hmode: self.saveData() if not self.cellsize: if not self.minWidth or not self.minHeight: print "No output dimension defined" return print "No explicit cellsize defined" outputAspectRatio = self.minWidth / float(self.minHeight) if self.targetAspectRatio < outputAspectRatio: self.cellsize = int(self.minHeight / self.vcells / self.tileAspectRatio) else: self.cellsize = int(self.minWidth / self.hcells) if self.hcells * self.cellsize < self.minWidth: self.cellsize += 1 if self.vcells * int(self.cellsize * self.tileAspectRatio+0.5) < self.minWidth: self.cellsize += 1 if self.filename == '': self.filename = "%s_%s_%d_x_%d_c%d.jpg" % (self.rootname, self.basename, self.hcells, self.vcells, self.cellsize) self.pngname = re.sub(r'\.\w+$', '.png', self.filename) self.width = self.cellsize * self.hcells self.height = (self.cellsize / self.tileAspectRatio) * self.vcells cellsizeX = int(self.width / self.hcells + 0.5) cellsizeY = int(self.height / self.vcells + 0.5) width = cellsizeX * self.hcells height = cellsizeY * self.vcells if self.verbose: print "Image Dimensions will be %d x %d (tiles = %dx%d pixels)" % (width, height, cellsizeX, cellsizeY) maxCellsize = max(cellsizeX,cellsizeY) htmlName = re.sub(r'\.jpg', '.html', self.filename) mosaic = Image.new("RGB", (width, height), "black") draw = ImageDraw.Draw(mosaic) markup = '' markup += "<img src=\"%s\" usemap=\"#mozmap\" border=0>\n" % (self.filename) markup +="<map name=\"mozmap\">\n"; if not self.hmode: for cell in self.cells: imgdat = self.finalimages[cell['iIdx']] x = cell['x'] y = cell['y'] img = self.getCroppedPhoto(imgdat['idx'], maxCellsize, cell['var']) img = img.resize((cellsizeX, cellsizeY), self.filter) if cell['flop'] and self.doflops: img = img.transpose(Image.FLIP_LEFT_RIGHT) if self.mixin > 0 and self.tint: # !! this causes the paste to break mask = Image.new("L",(cellsizeX,cellsizeY),int(self.mixin*255/100)) tint = Image.new("RGB", (cellsizeX, cellsizeY), tuple(cell['avg'])) img.paste(tint,(0,0),mask) mosaic.paste(img, (x*cellsizeX,y*cellsizeY)) markup += "<AREA SHAPE=rect COORDS=\"%d,%d,%d,%d\" href=\"%s\" TITLE=\"%s\">\n" % ( x*cellsizeX,y*cellsizeY,(x+1)*cellsizeX,(y+1)*cellsizeY, self.imageset.getImageWebpage(imgdat['idx']), self.imageset.getImageDesc(imgdat['idx']) ) # perform annotations if self.anno: # text = Magick::Draw.new pointsize = int(cellsizeX * 0.33) pointsize = max(9,pointsize) label = '%c%d' % (65+x,y+1) draw.text((x*cellsizeX+1,y*cellsizeY+1),label,(255,255,255)) else: # !! HMODE IN DEVELOPMENT - images are allowed to overlap if self.hbase != '': mosaic = Image.load(self.hbase).resize((width, height)) draw = ImageDraw.Draw(mosaic) for i,imgdat in enumerate(self.finalimages): cell = self.cells[imgdat['cellIdx']] x = cell['x'] y = cell['y'] markup += "<AREA SHAPE=rect COORDS=\"%d,%d,%d,%d\" href=\"%s\" TITLE=\"%s\">\n" % ( x*cellsizeX,y*cellsizeY,(x+1)*cellsizeX,(y+1)*cellsizeY, self.imageset.getImageWebpage(imgdat['idx']), self.imageset.getImageDesc(imgdat['idx']) ) img = self.getCroppedPhoto(imgdat['idx'], maxCellsize, cell['var']) img = img.resize((cellsizeX,cellsizeY)) if cell['flop'] and self.doflops: img = img.transpose(Image.FLIP_LEFT_RIGHT) mosaic.paste(img, (x*cellsizeX/self.resoX,y*cellsizeY/self.resoY, x*cellsizeX/self.resoX+cellsizeX, y*cellsizeY/self.resoY+cellsizeY)) # mosaic.composite!(img,x*cellsizeX/self.resoX,y*cellsizeY/self.resoY,Magick::OverCompositeOp) markup += '</map>' # output markup to file here... open(htmlName, "w").write(markup) if self.mixin > 0 and not self.tint: print "Mixing in %d%%..." % (self.mixin) bgpic = Image.open(self.basepic).resize((width, height), self.filter) mask = Image.new("L",(width,height),int(self.mixin*255/100)) mosaic.paste(bgpic,(0,0),mask) if self.grayscale: mosaic = mosaic.convert("L") if self.png: mosaic.save(self.pngname) if self.verbose: print "Saving JPEG %s" % (self.filename) mosaic.save(self.filename, quality=self.quality)
def main(): filename = sys.argv[-1] try: im = Image.load(filename) im.verify( ) #I perform also verify, don't know if he sees other types o defects im.close() #reload is necessary in my case im = Image.load(filename) im.transpose(PIL.Image.FLIP_LEFT_RIGHT) im.close() except: #manage excetions here sys.exit(0) f = imageio.imread(filename, as_gray=True) try: imageio.verify(f) # do stuff except IOError: # filename not an image file sys.exit(0) def img_estim(img, thrshld): is_light = np.mean(img) > thrshld #print(np.mean(img)) #return 'light' if is_light else os.remove(filename) if is_light == 0: os.remove(filename) img_estim(f, 40)
def is_pixel_eq(self, _image1: Image, _image2: Image, x: int, y: int): pixel_image1 = _image1.load()[x, y] pixel_image2 = _image2.load()[x, y] threshold = 60 if abs(pixel_image1[0]-pixel_image2[0])<threshold and abs(pixel_image1[1]-pixel_image2[1])<threshold and abs(pixel_image1[2]-pixel_image2[2])<threshold: return True return False
def encrypt(Image, byteArrays): pixelPosition = 0 encodeImageSize(Image, byteArrays) for x in range(Image.size[0]): for y in range(Image.size[1]): if x == 0 and y < 4: pass else: currentPixel = Image.load()[x, y] if pixelPosition < len(byteArrays): arrayPosition = pixelPosition // 2 newPixel = ( changeRGBA( currentPixel[0], byteArrays[arrayPosition][pixelPosition % 2 * 2 + 0]), changeRGBA( currentPixel[1], byteArrays[arrayPosition][pixelPosition % 2 * 2 + 1]), changeRGBA( currentPixel[2], byteArrays[arrayPosition][pixelPosition % 2 * 2 + 2]), changeRGBA( currentPixel[3], byteArrays[arrayPosition][pixelPosition % 2 * 2 + 3])) Image.load()[x, y] = newPixel elif pixelPosition < len(byteArrays) + 3: newPixel = (changeRGBA(currentPixel[0], 1), changeRGBA(currentPixel[1], 1), changeRGBA(currentPixel[2], 1), changeRGBA(currentPixel[3], 1)) Image.load()[x, y] = newPixel
def pilToNumpy(img: Image) -> np.ndarray: """ Fast load pillow image to numpy array Args: img: pillow image Returns: numpy array Raises: RuntimeError: if encoding failed References: https://habr.com/ru/post/545850/ """ img.load() # unpack data e = PIL.Image._getencoder(img.mode, "raw", img.mode) e.setimage(img.im) # NumPy buffer for the result shape, typestr = PIL.Image._conv_type_shape(img) data = np.empty(shape, dtype=np.dtype(typestr)) mem = data.data.cast("B", (data.data.nbytes, )) bufsize, s, offset = 65536, 0, 0 while not s: l, s, d = e.encode(bufsize) mem[offset:offset + len(d)] = d # noqa: E203 offset += len(d) if s < 0: raise RuntimeError("encoder error %d in tobytes" % s) return data
def tint_image(src: Image, color: tuple=(255, 255, 255)): src.load() r, g, b, alpha = src.split() gray = ImageOps.grayscale(src) result = ImageOps.colorize(gray, (0, 0, 0, 0), color) result.putalpha(alpha) return result
def get_image_and_mask(image: Image): """Splits the image into the displayed pixels and it's opacity mask. Args: image (Image): PIL.Image instance Returns: (tuple of Image): (image, mask) """ mask = None if image.mode == 'P': image = image.convert('RGBA') if image.mode in 'RGBA' and len(image.getbands()) == 4: image.load() image_alpha = image.split()[INDEX_ALPHA_CHANNEL] image_rgb = Image.new("RGB", image.size, color=(255, 255, 255)) mask = Image.new("1", image.size, color=1) image_rgb.paste(image, mask=image_alpha) mask.paste(0, mask=image_alpha) image = image_rgb else: # convert to supported image formats image.load() image_rgb = Image.new("RGB", image.size, color=(255, 255, 255)) image_rgb.paste(image) image = image_rgb return image, mask
def encrypt(Image, byteArrays): pixelPosition = 4 encodeImageSize(Image, byteArrays) for x in range(Image.size[0]): for y in range(Image.size[1]): if x == 0 and y < 4: pass else: currentPixel = Image.load()[x, y] if pixelPosition < len(byteArrays) * 2 + 8: arrayPosition = (pixelPosition - 8) // 2 print(arrayPosition) print(len(byteArrays)) print(byteArrays[arrayPosition]) newPixel = ( changeRGBA( currentPixel[0], byteArrays[arrayPosition][pixelPosition % 2 * 4 + 0]), changeRGBA( currentPixel[1], byteArrays[arrayPosition][pixelPosition % 2 * 4 + 1]), changeRGBA( currentPixel[2], byteArrays[arrayPosition][pixelPosition % 2 * 4 + 2]), changeRGBA( currentPixel[3], byteArrays[arrayPosition][pixelPosition % 2 * 4 + 3])) pixelPosition += 1 Image.load()[x, y] = newPixel
def to_RGB(image:Image)->Image: if image.mode == 'RGB':return image image.load() # required for png.split() background = Image.new("RGB", image.size, (255, 255, 255)) background.paste(image, mask=image.split()[3]) # 3 is the alpha channel file_name = 'tmp.jpg' background.save(file_name, 'JPEG', quality=80) return cv2.open(file_name)
def is_pixel_eq(self, _image1: Image, _image2: Image, x: int, y: int): pixel_image1 = _image1.load()[x, y] pixel_image2 = _image2.load()[x, y] threshold = 60 if abs(pixel_image1[0] - pixel_image2[0]) < threshold and abs( pixel_image1[1] - pixel_image2[1]) < threshold and abs( pixel_image1[2] - pixel_image2[2]) < threshold: return True return False
def is_image_truncated(image: Image) -> bool: """Returns True if the path refers to a truncated image Args: image: Returns: True if the image is truncated """ try: image.load() return False except (OSError, AttributeError): return True
def encodeImageSize(Image, byteArrays): characters = len(byteArrays) lengthByte = [0] * 32 for i in range(32, -1, -1): if characters >= 2**i: lengthByte[32 - i] = 1 characters -= 2**i # 8 pixels for i in range(8): currentPixel = Image.load()[0, i] r = changeRGBA(currentPixel[0], lengthByte[i * 4]) g = changeRGBA(currentPixel[1], lengthByte[i * 4 + 1]) b = changeRGBA(currentPixel[2], lengthByte[i * 4 + 2]) a = changeRGBA(currentPixel[3], lengthByte[i * 4 + 3]) Image.load()[0, i] = (r, g, b, a)
def ImageMask_printmask(Image, Mask, position = [0,0], colour=[0,0,0]): #Procedure to show a Mask in the Image ''' :param Image: main image for correcture, type: PIL.Image :param Mask: mask of text for positioning (only the most bright pixels): type: ndarray :param position: start position for mask [X, Y], type = integer :param colour: addition of colour to show mask (r, g, b), type = bite (0...255) ''' MaskHeight = len(Mask) MaskWidth = len(Mask[1]) pix = Image.load() draw = ImageDraw.Draw(Image) for x in range(MaskWidth): for y in range(MaskHeight): if Mask[y][x]: red = pix[position[0] + x, position[1] + y][0] + colour[0] green = pix[position[0] + x, position[1] + y][1] + colour[1] blue = pix[position[0] + x, position[1] + y][2] + colour[2] if red > 255: red = 255 if green > 255: green = 255 if blue > 255: blue = 255 if red < 0: red = 0 if green < 0: green = 0 if blue < 0: blue = 0 draw.point((position[0] + x, position[1] + y), (red, green, blue))
def toArray(filename): im = Image.load(filename) im = im.convert('L') arr = np.fromiter(iter(im.getdata()), np.uint8) arr.resize(im.height, im.width) print(arr)
def get_all_pics(origin_pic: Image, row_height: int) -> List[List[PicInfo]]: bin_pic = origin_pic.convert('L').point(lambda x: 1 if x > 130 else 0, mode='1') # bin_pic.show() opx = origin_pic.load() px = bin_pic.load() x_len, y_len = bin_pic.size row_num = y_len // row_height all_pics = [] for y_mid in [ int(i * row_height + row_height / 2) for i in range(row_num) ]: row_pics = [] x = 0 while x < x_len: if px[x, y_mid]: num_box = find_area((x, y_mid), bin_pic) # draw_box(opx, (num_box[0], num_box[1]), (num_box[2], num_box[3])) row_pics.append( PicInfo( img=pad_image(origin_pic.crop(num_box)), x_mid=(num_box[2] + num_box[0]) // 2, y_mid=y_mid, is_yellow=is_pixel_yellow( opx[(x + 1, y_mid)]) # +1 to skip board )) x = num_box[2] x += 1 all_pics.append(row_pics) return all_pics
def ImageMask_statistic(Image, Mask, position = [0,0]): ''' :param Image: main image for correcture, type: PIL.Image :param Mask: mask of text for positioning (only the most bright pixels): type: ndarray :param position: start position for mask [X, Y], type = integer :return: mean bright of pixels inside mask [0] and outside mask [1] ''' MaskHeight = len(Mask) MaskWidth = len(Mask[1]) inmask, outofmask = 0, 0 #Накопленный черный и белый цвета pix = Image.load() for x in range(MaskWidth): for y in range(MaskHeight): red = pix[position[0] + x, position[1] + y][0] blue = pix[position[0] + x, position[1] + y][1] green = pix[position[0] + x, position[1] + y][2] S = (red + blue + green) // 3 if Mask[y][x]: inmask += S else: outofmask += S inmask = inmask/np.sum(Mask) outofmask = outofmask / (np.size(Mask) - np.sum(Mask)) return [inmask, outofmask]
def compare_images( image_1: Image, image_2: Image, marked_image: bool = False, marked_color: tuple = (255, 0, 0)) -> list: """ Сравниваем полученные изображения и возвращаем результирующее изображение """ # Одинаковые участки закрашиваются черным result = [ImageChops.difference(image_1, image_2)] # Два различных пикселя заменить на marked_color (по умолчанию: красный) if marked_image: image_copy = ImageChops.duplicate(image_1) # Создаем холст draw = ImageDraw.Draw(image_copy) width, height = image_copy.size # Выгружаем значения пикселей pixels_1 = image_copy.load() pixels_2 = image_2.load() for x in range(width): for y in range(height): result_pixel = pixels_1[x, y] if pixels_1[x, y] == pixels_2[ x, y] else marked_color draw.point((x, y), result_pixel) result.append(image_copy) return result
def subpixel_conversion(pic: Image) -> Image: """ Function that converts from an rgb image to a rgb image that imitates the way that a LCD screen uses subpixels to display things. :param pic: The image to convert as an Image :return: The new image as an Image """ width = pic.size[0] * 3 hieght = pic.size[1] * 3 new_pic = Image.new('RGB', (width, hieght), color='black') pixmap = pic.load() new_pixmap = new_pic.load() for i in range(pic.size[0]): # for every col of the original image for j in range(pic.size[1]): # For every row of the original image real_x = i * 3 real_y = j * 3 color = pixmap[i, j] for k in range(3): # for every color for l in range(3): # for every pixel of color if k == 0: new_pixmap[real_x + k, real_y + l] = (color[0], 0, 0) elif k == 1: new_pixmap[real_x + k, real_y + l] = (0, color[1], 0) elif k == 2: new_pixmap[real_x + k, real_y + l] = (0, 0, color[2]) return new_pic
def colorFilter(Image, NewIm): width = Image.size[0] # define W and H height = Image.size[1] photo = Image.load() # photo = photo.convert('RGB') NewPhoto = NewIm.load() for y in range(0, height): # each pixel has coordinates row = "" for x in range(0, width): RGB = photo[x, y] R, G, B = RGB # now you can use the RGB value # print(R,G,B) if (R > 80 and G < 50 and B < 50) or ((R > 140) and ( (R - G > 20) or G - R > 20) and (R - B > 20 or B - R > 20)): NewPhoto[x, y] = (0, 0, 0) # Bolding the Img try: for X in range(0, 3): for Y in range(0, 3): NewPhoto[x - 3 + X, y - 3 + Y] = (0, 0, 0) except: NewPhoto[x, y] = (0, 0, 0) else: NewPhoto[x, y] = (255, 255, 255) return NewPhoto
def image_to_black_and_colored_pixel_strings(image: Image) -> (list, list): """ Analyze colors in Pillow image, return a tuple of pixel array matching black pixels, and a pixel array matching red/yellow pixels. E-ink is a passive display, so we want to mark out all black and potentially red/yellow pixels to draw. The color of the colored array doesn't matter since the e-ink displays pnly support a optional second color like red or yellow. The two string arrays shall be equally long, and represent the amount od pixels in the image. :param image: Pillow Image extract pixels from :return: (list, list) a tuple concisting of a list matching black pixels, and colored pixels """ pixels_black = [] pixels_color = [] pixel_access = image.load() # Used for reading pixel value of a Pillow image for y in range(image.height): for x in range(image.width): r, g, b = pixel_access[x, y] color = catogerize_rgb_as_color(r, g, b) if color == 'black': pixels_black.append(1) pixels_color.append(0) elif color == 'yellow' or color == 'red': pixels_black.append(0) # Don't color in black pixels since we are going to draw a colored pixels_color.append(1) else: pixels_black.append(0) pixels_color.append(0) return pixels_black, pixels_color
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)
def encode(image: Image, message: bytes): image = image.convert("RGB") pixels = image.load() available = image.width * image.height * 3 size = len(message) if available <= size * 8 + 8 * len( b"\x90\xbfhttps://github.com/evil-steganography/evil-stego-1"): raise NotEnoughValuesException("Needs {:d} bits worth of space, only got {:d}" \ .format(size * 8 + 8 * len(b"\x90\xbfhttps://github.com/evil-steganography/evil-stego-1"), available)) seed = [random.getrandbits(8) for i in range(4)] random.seed(bytes(seed)) valid_spots = [] for channel in range(3): for y in range(image.height): for x in range(image.width): valid_spots.append((x, y, channel)) metadata = b"\x90\xbfhttps://github.com/evil-steganography/evil-stego-1" + bytes( seed) + pack("<I", size) c = 0 for byte in metadata: write_byte(pixels, byte, valid_spots[c:c + 8]) c += 8 locations = random.sample(valid_spots[c:], size * 8 + 1) c = 0 for byte in message: write_byte(pixels, byte, locations[c:c + 8]) c += 8 return image
def paint_nodes(image: Image, nodes: set): color = (0, 255, 0) image = image.convert('RGB') image_pixels = image.load() for node in nodes: image_pixels[node.position] = color return image
def save_image(text_area: Text, image: Image, result: list, output_file: str): insert_text(text_area, "\n\nSaving Image...") image = image.convert('RGB') image_pixels = image.load() result_path = [n.position for n in result] length = len(result_path) for i in range(0, length - 1): a = result_path[i] b = result_path[i + 1] # Blue - red r = int((i / length) * 255) px = (r, 0, 255 - r) if a[0] == b[0]: # X equal, vertical line for x in range(min(a[1], b[1]), max(a[1], b[1]) + 1): image_pixels[a[0], x] = px elif a[1] == b[1]: # Y equal, horizontal line for y in range(min(a[0], b[0]), max(a[0], b[0]) + 1): image_pixels[y, a[1]] = px image.save(output_file) output_tree = output_file.split("/") filename = output_tree[len(output_tree) - 1] destination = "" for i in range(len(output_tree) - 1): destination += output_tree[i] + "/" insert_text(text_area, "\nImage saved in " + destination + " as " + filename + "\n")
def pasteImage(img: Image, frame: LCD12864, invert=False): px = img.load() _pixel = frame.pixel for y in range(64): for x in range(128): color = 0 if (px[x,y]==0)!=invert else 1 _pixel(x, y, color)
def get_symbol(self, symbol): symbol_directory = self.directory + symbol file_name = random.choice(os.listdir(symbol_directory)) return Image.load(file_name)
def colorshift( src_img: Image, zoom=1, cx = -1, cy = 1, dx = 0, dy = 0, zf = 0.5, kx = 1.5, ky = 1.0, normalization = 9 ) -> Image: (w, h) = src_img.size dst_img = src_img.copy() src = src_img.load() dst = dst_img.load() for x in progress(w): for y in range(h): zx = kx * (x - w / 2) / (zf * zoom * w) + dx zy = ky * (y - h / 2) / (zf * zoom * h) + dy i = sum(src[x, y])/normalization while zx * zx + zy * zy < 4 and i > 1: tmp = zx * zx - zy * zy + cx zy, zx = 2.0 * zx * zy + cy, tmp i -= 1 # convert byte to RGB (3 bytes), kinda magic to get nice colors # this works in python 2, but in 3 we lose short (2 byte) ints :( # dst[x, y] = (i << 21) + (i << 10) + (i * 8) # instead, rely on precomputed mapping: dst[x, y] = __palette__[int(i)] return dst_img
def discover(img: Image) -> str: """ Attempts to discover hidden message in the Image. """ lsbits = "" # least significant bits width, height = img.size pixels = img.load() y = 268 print(img.mode) print(width) print(height) if img.mode == "P": for x in range(width): p = pixels[x,y] lsbits += bin(p)[-1] elif img.mode == "RGB": for x in range(1, width): r, g, b = pixels[x,y] lsbits += bin(r)[-1] lsbits += bin(g)[-1] lsbits += bin(b)[-1] elif img.mode == "RGBA": for x in range(1, width): for y in range(height): r, g, b, a = pixels[x,y] lsbits += bin(r)[-1] lsbits += bin(g)[-1] lsbits += bin(b)[-1] lsbits += bin(a)[-1] chars = chararray(lsbits) print(len(chars)) return chars
def image_to_bytes(image: Image) -> bytes: """ Gets the Image object and converts it to tuple with widht, height and bytes with the image data :param image: The image to be converted :rtype: tuple """ pixels = image.load() width, height = image.size imagebytes = bytearray() imagebytes.extend((width).to_bytes(2, byteorder='big')) imagebytes.extend((height).to_bytes(2, byteorder='big')) bytecounter = 0 mbyte = 0 for y in range(height): for x in range(width): _, _, _, alpha = pixels[x, y] if (alpha > 0): mbyte = mbyte | (1 << bytecounter) bytecounter = bytecounter + 1 if bytecounter >= 8: imagebytes.append(mbyte) bytecounter = 0 mbyte = 0 return bytes(imagebytes)
def get_slider_edge_position_by_alpha(image: Image, alpha=(80, 254), show=False) -> np.ndarray: """ 根据边界透明度获取小滑块 边界 @param image: 闭 @param alpha: 透明度 开区间 @param show: 是否画图 方便调试 @return: numpy.ndarray 二维矩阵,缺口边界为1,其他为0。 横向为列,纵向为行。左上角为原点 """ pix = image.load() width = image.size[0] height = image.size[1] positions = [] position_arrays = np.zeros((height, width), dtype=np.int) # 高度为行 宽度为列 for x in range(width): for y in range(height): r, g, b, a = pix[x, y] if a >= alpha[0] and a <= alpha[1]: # 阴影为半透明 0 为全透明 255为不透明 positions.append([x, y]) position_arrays[y, x] = 1 if show: x = [position[0] for position in positions] y = [height - position[1] for position in positions] plt.xlim(right=width, left=0) plt.ylim(top=height, bottom=0) plt.plot(x, y, "ro") plt.show() return position_arrays
def calculate_gradient(image: Image): grad_image = image.copy() draw = ImageDraw.Draw(grad_image) pix = image.load() width = image.size[0] height = image.size[1] x_grad_image = image.copy() x_draw = ImageDraw.Draw(x_grad_image) for y in range(height): for x in range(1, width): r = g = b = abs(pix[x, y][0] - pix[x - 1, y][0]) x_draw.point((x, y), (r, g, b)) y_grad_image = image.copy() y_draw = ImageDraw.Draw(y_grad_image) for x in range(width): for y in range(1, height): r = g = b = abs(pix[x, y][0] - pix[x, y - 1][0]) y_draw.point((x, y), (r, g, b)) x_pix = x_grad_image.load() y_pix = y_grad_image.load() for x in range(width): for y in range(height): r = g = b = int(sqrt(x_pix[x, y][0]**2 + y_pix[x, y][0]**2)) draw.point((x, y), (r, g, b)) return grad_image
def image_to_emoji_lines(image: Image, emojiset: Dict[str, str], max_chars_per_line: int = 67, output: Optional[Any] = None, spaced: bool = False) -> List[str]: palette, emoji_names = zip(*[(colorhex_to_tuple(c), e) for e, c in emojiset.items()]) palette = list(palette) emoji_names = list(emoji_names) # pad palette to 256 elements, because PIL needs it like that if len(palette) < 256: palette += [palette[0]] * (256 - len(palette)) if image.width > max_chars_per_line: image = resize_to_width(image, max_chars_per_line) image = quantize(image, palette) if output: image.save(output, "PNG") pix = image.load() lines: List[str] = [] for y in range(image.height): emojis = [] for x in range(image.width): # pix[x, y] returns a palette index emojis.append(emoji_names[pix[x, y]]) lines.append((" " if spaced else "").join(emojis)) return lines
def OneDimensionalImage(Image): # this is the 1d array that we will fill with image values # values read from right to left ReturnArray = [] ImageArray = Image.load() for y in range(0, Image.size[1]): for x in range(0, Image.size[0]): Pixel = ImageArray[x, y] # white has value 0 and black has value 1 ReturnArray.append(1.0 - (Pixel / 255.0)) return ReturnArray
def find_center(img, color=(255,0,0)): szx, szy = img.size px = img.load() cr, cg, cb = color mx, my = (0,0) n = 0 for x in range(szx): for y in range(szy): r,g,b,a = px[x,y] if cr==r and cg==g and cb==b: #print x,y mx += x my += y n += 1 #print "med:", mx/n, my/n m = (mx/n, my/n) #return map(lambda x: int(round(x)), m) return m
def load_image(filename): image = Image.load(filename) return image
def write_glyph(f, ff_name, h, n): iname = "{}.{:03}.png".format(ff_name, n) if not os.path.exists(iname): h.char_widths[n] = 0 h.char_offsets[n] = f.tell() else: img = Image.load(iname) width,height = img.size if h.max_width < width: h.max_width = width if h.max_height < height: h.max_height = height h.char_widths[n] = width h.char_offsets[n] = f.tell() y = 0 while y < height: x = 0 while 1: byte = 0b00000000 ind = rpal[img.getpixel((x,y))] byte = byte | (ind << 6) x += 1 if x == width: write_uint8(f, byte) break ind = rpal[img.getpixel((x,y))] byte = byte | (ind << 4) x += 1 if x == width: write_uint8(f, byte) break ind = rpal[img.getpixel((x,y))] byte = byte | (ind << 2) x += 1 if x == width: write_uint8(f, byte) break ind = rpal[img.getpixel((x,y))] byte = byte | (ind << 0) x += 1 if x == width: write_uint8(f, byte) break write_uint8(f, byte) y += 1
indicoio.fer('FILEPATH') Formatting images using skimage import skimage.io import indicoio pixel_array = skimage.io.imread('FILEPATH') indicoio.fer(pixel_array) Formatting images using PIL and numpy from PIL import Image import numpy as np import indicoio image = Image.load('FILEPATH') pixel_array = np.array(image) indicoio.fer(pixel_array) #facial recognition import indicoio indicoio.config.api_key = '75b93ed62df0c77a6e58c8ebb1bb71f2' # single example indicoio.fer("<IMAGE>") # batch example indicoio.fer([
def cut_box(lft,up,rght,lwr, Image): Image.load() box = (lft, up, rght ,lwr) i = Image.crop(box) return i