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
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
def create_captcha_image(self, chars, background): """Create the CAPTCHA image itself. :param chars: text to be generated. :param background: color of the background. The color should be a tuple of 3 numbers, such as (0, 255, 255). """ image = Image.new('RGB', (self._width, self._height), background) images = [] for c in chars: images.append(self._draw_character(c)) text_width = sum([im.size[0] for im in images]) width = max(text_width, self._width) average = int(text_width / len(chars)) # 平均每个字符的所占的像素宽度 rand = int(0.2 * average) # offset = int(0.1 * average) # 水平上的偏移 x # 字符与字符的间距,紧凑可以按需调整 for i, txt_im in enumerate(images): w, h = txt_im.size c_color = random_color(70, 150) # 下面的 x,y表示的是image_txt的左上角在image上的坐标 x, y = (offset, int((self._height - h) / 2)) image.paste(colorize(txt_im, (0, 0, 0), c_color), (x, y), txt_im) offset = offset + w + random.randint(-rand,0) if width > self._width: image = image.resize((self._width, self._height)) return image
def neighbor(S, atoms, colors, wmin=8, hmin=8, random=random): """Get neighbor state of S.""" T = S.copy() atom = random.choice(atoms) # Affine transform -- Rotate atom = atom.rotate(random.randrange(360)) try: alpha = atom.getchannel("A") except ValueError: alpha = None # Colorize atom = colorize(atom.convert("L"), random.choice(colors), random.choice(colors)) if alpha is not None: atom.putalpha(alpha) # Affine transform -- Scale f = random.random() w = int(max(wmin, f * min(S.width, atom.width))) h = int(max(hmin, f * min(S.height, atom.height))) atom = atom.resize((w, h), Image.LANCZOS) # Affine transform -- Translate x = random.randrange(T.width - atom.width) y = random.randrange(T.height - atom.height) T.paste(atom, (x, y), atom) # Mutated image return T
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 run(self): for frame_no in range(self.FPS * self.length): frame = cast_to_uint8(self.get_next_frame(dt=1. / self.FPS)) img = Image.fromarray(frame, 'L') if self.color_palette: img = colorize(img, **self.color_palette) img.save(f'{self.file_name}_{frame_no}.png') for secondary_output_name, secondary_output_generator in self.secondary_outputs: secondary_frame = cast_to_uint8(secondary_output_generator(0)) Image.fromarray(secondary_frame, 'L').save(f'{self.file_name}_{secondary_output_name}_{frame_no}.png')
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)
def tintImage(img, tint): i = colorize(grayscale(img), (0,0,0), tint) i.putalpha(img.split()[3]) return i
def tintImage(img, tint): i = colorize(grayscale(img), (0, 0, 0), tint) i.putalpha(img.split()[3]) return i
def analyse(self): instructions = self.brother_file.read() for instruction in chunker(instructions): for opcode in OPCODES.keys(): if instruction.startswith(opcode): opcode_def = OPCODES[opcode] if opcode_def[0] == 'init': self.mwidth, self.mheight = None, None self.raster_no = None self.black_rows = [] self.red_rows = [] payload = instruction[len(opcode):] logger.info(" {} ({}) --> found! (payload: {})".format( opcode_def[0], hex_format(opcode), hex_format(payload))) if opcode_def[0] == 'compression': self.compression = payload[0] == 0x02 if 'raster' in opcode_def[0]: rpl = bytes(payload[2:]) # raster payload if self.compression: row = bytes() index = 0 while True: num = rpl[index] if num & 0x80: num = num - 0x100 if num < 0: num = -num + 1 row += bytes([rpl[index + 1]] * num) index += 2 else: num = num + 1 row += rpl[index + 1:index + 1 + num] index += 1 + num if index >= len(rpl): break else: row = rpl if opcode_def[0] == 'raster': self.black_rows.append(row) else: # 2-color if payload[0] == 0x01: self.black_rows.append(row) elif payload[0] == 0x02: self.red_rows.append(row) else: raise NotImplementedError("color: 0x%x" % payload[0]) if opcode_def[0] == 'expanded': self.two_color_printing = bool(payload[0] & (1 << 0)) self.cut_at_end = bool(payload[0] & (1 << 3)) self.high_resolution_printing = bool(payload[0] & (1 << 6)) if opcode_def[0] == 'media/quality': self.raster_no = struct.unpack('<L', payload[4:8])[0] self.mwidth = instruction[len(opcode) + 2] self.mlength = instruction[len(opcode) + 3] * 256 fmt = " media width: {} mm, media length: {} mm, raster no: {} rows" logger.info( fmt.format(self.mwidth, self.mlength, self.raster_no)) if opcode_def[0] == 'print': logger.info("Len of black rows: %d", len(self.black_rows)) logger.info("Len of red rows: %d", len(self.red_rows)) def get_im(rows): if not len(rows): return None size = (len(rows[0]) * 8, len(rows)) data = bytes(b''.join(rows)) data = bytes([2**8 + ~byte for byte in data]) # invert b/w im = Image.frombytes("1", size, data, decoder_name='raw') return im im_black, im_red = (get_im(rows) for rows in (self.black_rows, self.red_rows)) if not self.two_color_printing: im = im_black else: im_black = im_black.convert("RGBA") im_red = im_red.convert("L") im_red = colorize(im_red, (255, 0, 0), (255, 255, 255)) im_red = im_red.convert("RGBA") pixdata_black = im_black.load() width, height = im_black.size for y in range(height): for x in range(width): # replace "white" with "transparent" if pixdata_black[x, y] == (255, 255, 255, 255): pixdata_black[x, y] = (255, 255, 255, 0) im_red.paste(im_black, (0, 0), im_black) im = im_red im = im.transpose(Image.FLIP_LEFT_RIGHT) img_name = self.filename_fmt.format( counter=self.page_counter) im.save(img_name) print('Page saved as {}'.format(img_name)) self.page_counter += 1
red, green, blue = inverted_image.split() del inverted_image new_image: Image = Image.merge('RGBA', (red, green, blue, alpha)) # save new image to new dir new_image.save(join(to_path, icon)) del new_image, red, green, blue, alpha for icon in files: printProgressBar(files.index(icon), len(files) - 1, prefix='Progress:', suffix='Complete', length=50) if icon in ignore_files: continue image: Image = Image.open(join(from_path, icon)) if image.mode == 'RGBA': red, green, blue, alpha = image.split() del image # inverted image temp_icon: Image = Image.merge('RGB', (red, green, blue)) red, green, blue = colorize(temp_icon.convert("L"), black="#3ff23f", white="#3ff23f").split() del temp_icon new_image: Image = Image.merge('RGBA', (red, green, blue, alpha)) # save new image to new dir new_image.save(join(contrast_path, icon)) del new_image, red, green, blue, alpha
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))