chars = chain.from_iterable([y + (Unicode[y[0]],) for y in x.cmap.items()] for x in ttf["cmap"].tables) char_list = (list(chars)) char_list = tqdm(char_list) # load font # 讀取字體 font = ImageFont.truetype(args.otf, args.font_size) # draw font # 畫出字體 num = 0 for i in char_list: char_unicode = chr(i[0]) origin = [0, 0] txt = Image.new('RGB', (args.image_size, args.image_size), (255, 255, 255)) draw = ImageDraw.ImageDraw(txt) size = draw.textsize(char_unicode,font=font) if args.image_size - size[0] < 0: origin[0] = args.image_size - size[0] else: origin[0] = 0 if args.image_size - size[1] < 0: origin[1] = args.image_size - size[1] else: origin[1] = 0 # print(size) draw.text(tuple(origin), char_unicode, font=font, fill=0) # check if the image is whole white # 看看圖片是否全白
if __name__ == '__main__': path = r"D:\shujuji\明星人脸识别\霍建华" detector = Detector() count = 1 for image in os.listdir(path): # print(os.listdir(path)) # print(image) image_path = os.path.join(path, image) # print(image_path) img1 = pimg.open(image_path) img1 = img1.convert("RGB") boxes = detector.detect(img1) draw_img1 = draw.ImageDraw(img1) # count = str(image_path[-7:-4]) # print(count) for box in boxes: x1 = int(box[0]) y1 = int(box[1]) x2 = int(box[2]) y2 = int(box[3]) # print(box[4]) # draw_img1.rectangle((x1,y1,x2,y2),outline="red",width=3) img1 = img1.crop((x1,y1,x2,y2)) # img1.show() img1.save(r"D:\shujuji\明星人脸识别\霍建华0\{}.jpg".format(count)) plt.imshow(img1) # plt.show() plt.pause(1)
def select_ocr_image( infiles, output_file, log, context): """Select the image we send for OCR. May not be the same as the display image depending on preprocessing. This image will never be shown to the user.""" image = infiles[0] options = context.get_options() pageinfo = get_pageinfo(image, context) with Image.open(image) as im: from PIL import ImageColor from PIL import ImageDraw from decimal import Decimal white = ImageColor.getcolor('#ffffff', im.mode) #pink = ImageColor.getcolor('#ff0080', im.mode) draw = ImageDraw.ImageDraw(im) xres, yres = im.info['dpi'] log.debug('resolution %r %r', xres, yres) if not options.force_ocr: # Do not mask text areas when forcing OCR, because we need to OCR # all text areas mask = None # Exclude both visible and invisible text from OCR if options.redo_ocr: mask = True # Mask visible text, but not invisible text for textarea in pageinfo.get_textareas(visible=mask, corrupt=None): # Calculate resolution based on the image size and page dimensions # without regard whatever resolution is in pageinfo (may differ or # be None) bbox = [float(v) for v in textarea] xscale, yscale = float(xres) / 72.0, float(yres) / 72.0 pixcoords = [bbox[0] * xscale, im.height - bbox[3] * yscale, bbox[2] * xscale, im.height - bbox[1] * yscale] pixcoords = [int(round(c)) for c in pixcoords] log.debug('blanking %r', pixcoords) draw.rectangle(pixcoords, fill=white) #draw.rectangle(pixcoords, outline=pink) if options.mask_barcodes or options.threshold: pix = leptonica.Pix.frompil(im) if options.threshold: pix = pix.masked_threshold_on_background_norm() if options.mask_barcodes: barcodes = pix.locate_barcodes() for barcode in barcodes: decoded, rect = barcode log.info('masking barcode %s %r', decoded, rect) draw.rectangle(rect, fill=white) im = pix.topil() del draw # Pillow requires integer DPI dpi = round(xres), round(yres) im.save(output_file, dpi=dpi)
vector["buf"] = bufImage vector["dbuf"] = bufImage for element in calibration: utils.calc_dist(targetMask, vector["dbuf"], element_scans[element], vector[element]) for vector in calibratedVectors: utils.compare_dist(targetMask, outputImage, mineral_dists, vector["index"], vector["dbuf"]) mapImage = Image.new("P", (tWidth, tHeight), 0) mapImage.putpalette(constants.palette) mineralPixelCounts = {} for mineral in mineralNames: mineralPixelCounts[mineral] = 0 d = ImageDraw.ImageDraw(mapImage) for x in range(0, tWidth): for y in range(0, tHeight): color = outputImage[y,x] d.point((x,y), fill=int(color)) if color != 0: mineralPixelCounts[mineralNames[color-1]] += 1 mapImage.save(targetObject + "_mineralmap.gif") with open(targetObject + "_mineralcounts.json", "w") as outfile: json.dump(mineralPixelCounts, outfile) Image.fromarray(mineral_dists, mode="I").save(targetObject + "_confidence.tif") # legendImage = Image.new("P", (256, 256), 0)
def gen_image(self, draw_text=True, squaresize=100): """ writes this color table (palette) to a png image. """ from PIL import Image, ImageDraw imgside_length = math.ceil(math.sqrt(len(self.palette))) imgsize = imgside_length * squaresize dbg("generating palette image with size %dx%d", imgsize, imgsize) palette_image = Image.new('RGBA', (imgsize, imgsize), (255, 255, 255, 0)) draw = ImageDraw.ImageDraw(palette_image) # dirty, i know... text_padlength = len(str(len(self.palette))) text_format = "%%0%dd" % (text_padlength) drawn = 0 # squaresize 1 means draw single pixels if squaresize == 1: for y in range(imgside_length): for x in range(imgside_length): if drawn < len(self.palette): r, g, b = self.palette[drawn] draw.point((x, y), fill=(r, g, b, 255)) drawn = drawn + 1 # draw nice squares with given side length elif squaresize > 1: for y in range(imgside_length): for x in range(imgside_length): if drawn < len(self.palette): sx = x * squaresize - 1 sy = y * squaresize - 1 ex = sx + squaresize - 1 ey = sy + squaresize r, g, b = self.palette[drawn] # begin top-left, go clockwise: vertices = [(sx, sy), (ex, sy), (ex, ey), (sx, ey)] draw.polygon(vertices, fill=(r, g, b, 255)) if draw_text and squaresize > 40: # draw the color id # insert current color id into string ctext = text_format % drawn tcolor = (255 - r, 255 - b, 255 - g, 255) # draw the text # TODO: use customsized font draw.text((sx + 3, sy + 1), ctext, fill=tcolor, font=None) drawn = drawn + 1 else: raise Exception("fak u, no negative values for squaresize pls.") return palette_image
FILE = "logo".join(DIRS1) LGO_PTH = LOGO_PATH + FILE LOGO = Image.open(LGO_PTH) LGO = LOGO.size for FILE in DIRS: image_path = PATH + FILE # a = f.append(file) # print a print(image_path) im = Image.open(image_path) print(im.size) if CHOICE == 1: transparent = Image.new("RGBA", im.size) draw = ImageDraw.ImageDraw(transparent, "RGBA") font = ImageFont.truetype("arial.ttf", TXT_SIZE) a = font.getsize(TXT) print("getsize", a) draw.line((0, 0) + im.size, fill=(160, 161, 161)) draw.line((0, im.size[1], im.size[0], 0), fill=(161, 161, 161)) if CHOICE == 1: draw.text((im.size[0] / 2 - a[0] / 2, im.size[1] / 2), TXT, font=font, fill=(255, 255, 255)) mask = transparent.convert("L").point( lambda x_param: min(x_param, TRANS)) transparent.putalpha(mask)
def test_mode_mismatch(self): im = hopper("RGB").copy() self.assertRaises(ValueError, lambda: ImageDraw.ImageDraw(im, mode="L"))
for vector in calibratedVectors: compare_dist(dTargetMask, device_outputImage, d_mineral_dists, vector["index"], vector["dbuf"]) device_outputImage.to_host() mapImage = Image.new("P", (tWidth, tHeight), 0) mapImage.putpalette(palette) mineralPixelCounts = {} for mineral in mineralNames: mineralPixelCounts[mineral] = 0 d = ImageDraw.ImageDraw(mapImage) for x in range(0, tWidth): for y in range(0, tHeight): color = outputImage[y,x] d.point((x,y), fill=int(color)) if color != 0: mineralPixelCounts[mineralNames[color-1]] += 1 mapImage.save(targetObject + "_mineralmap.gif") with open(targetObject + "_mineralcounts.json", "w") as outfile: json.dump(mineralPixelCounts, outfile) @cuda.jit def map_mask(inImage, maskImage, outImage): for x in range(0, tWidth):
max_side_len = max(w, h) #搞成正方形 try: cx = (x11 + x22) / 2 cy = (y22 + y11) / 2 x1 = cx - max_side_len / 2 y1 = cy - max_side_len / 2 x2 = x1 + max_side_len y2 = y1 + max_side_len #计算偏移量,(实际框-建议框)/正方形边长 offset_x1 = float((x11 - x11) / max_side_len) offset_y1 = float((y11 - y11) / max_side_len) offset_x2 = float((x22 - x22) / max_side_len) offset_y2 = float((y22 - y22) / max_side_len) draw_img = Draw.ImageDraw(img) # draw_img.rectangle((box1[0, 0], box1[0, 1], box1[0, 2], box1[0, 3]), outline="green", width=5) # # draw_img.rectangle((x11, y11, x22, y22), outline="red", width=5) draw_img.rectangle((x1, y1, x2, y2), outline="blue", width=5) plt.imshow(img) plt.pause(1) w_img, h_img = img.size if x1 > 0 and y1 > 0 and x2 < w_img and y2 < h_img: # 保存图片,写标签
def draw_text(img, text, xy=(0, 0), fill='black', font=None): font = font or default_font draw = ImageDraw.ImageDraw(img) draw.text(xy, text=text, fill=fill, font=font) return img
def pen(self) -> draw.ImageDraw: """Gets an object capable of drawing over the projection.""" return draw.ImageDraw(self.image)
def print_boxes(im, outpath, dets, printthresh=None): if type(im) == str: im = Image.open(im) width = im.width height = im.height draw = ImageDraw.ImageDraw(im) mfontsize = int( min(100, max(8, int(max(width, height) / 1000.0 * 14))) / 2) if (mfontsize not in fontDict): tl.acquire() fontDict[mfontsize] = ImageFont.truetype(font=myfont, size=mfontsize * 2) tl.release() font = fontDict[mfontsize] for det in dets: prob = det.prob if det.prob is not None else 0 cls_name = det.cls if (cls_name not in colordict): tl.acquire() random.seed(salt + cls_name) color = np.array( [random.random(), random.random(), random.random()]) color = color - color.min() color = color / color.max() * 255.0 color = tuple(color.astype('i')) colordict[cls_name] = 'rgb({},{},{})'.format(*color) tl.release() color = colordict[cls_name] if printthresh == None or printthresh <= prob: det_loc = location(relloc=(det.xc, det.yc, det.w, det.h), picsize=(width, height)) absloc = det_loc.getabsloc() det_w = absloc[2] - absloc[0] det_h = absloc[3] - absloc[1] outputfmt = '{name:s} .{prob:02}' if type( cls_name) == str else u'{name:s} .{prob:02}' outputstr = outputfmt.format(name=cls_name, prob=int(100 * prob)) linewidth = int( max(4, min(max(width, height) / 480.0, max(det_w, det_h) / 100.0))) str_w, str_h = draw.textsize(text=outputstr, font=font) xy = (absloc[0], absloc[1]) if absloc[1] < linewidth + str_h else (absloc[0], absloc[1] - linewidth - str_h) draw.text(xy=xy, text=outputstr, fill=color, font=font) for offset in xrange(linewidth): draw.rectangle((absloc[0] - offset, absloc[1] - offset, absloc[2] + offset, absloc[3] + offset), outline=color) im.save(outpath, quality=95, compress_level=1)
def drawImage(self, author_id: int, author: str, text: str, avatar_url: str) -> str: from os import path """ :param self: self :param author: автор цитаты :param text: текст цитаты :param avatar_url: ссылка на аватар :return: путь к файлу. """ w = textwrap.TextWrapper(width=60) dark_scheme = ( (0, 0, 0, 0), 'rgb(255,255,255)' ) light_scheme = ( (255, 255, 255, 255), 'rgb(128,128,128)' ) use_bg_img: bool = False background = Image.open(self.get_wallpaper(author_id)) img = Image.new("RGBA", (1280, 720), dark_scheme[0]) draw = ImageDraw.Draw(img) theme = dark_scheme if theme is not light_scheme and not use_bg_img: draw.rectangle((0, 0, img.size), fill='rgb(0,0,0)') img.paste(background) font = ImageFont.truetype(path.join(self.bot.get_resource_folder(), self.name, "font.ttf"), size=30) watermark = Image.new("RGBA", img.size) waterdraw = ImageDraw.ImageDraw(watermark, "RGBA") watermark_font = ImageFont.truetype(path.join(self.bot.get_resource_folder(), self.name, "font.ttf"), size=70) time = f'Время: {datetime.datetime.today().strftime("%H:%M:%S")}' date = f'Дата: {datetime.datetime.today().strftime("%Y-%m-%d")}' draw.text((300, 200), f"© {author}", fill=theme[1], font=font) save_to = os.path.join(self.res_dir, f'avatar_{author_id}.png') avatar = Image.open(downloadImg(avatar_url, save_to), 'r').convert("RGBA") self.crop_to_circle(avatar) avatar.convert("RGB") # avatar = ImageOps.expand(avatar, border=(3,3,3,3), fill="black") h = 250 lines = w.wrap(text) for line in text.split("\n"): if len(line) > 60: line = w.fill(line) print(line) width, height = font.getsize(line) draw.text((300, h), line, fill=theme[1], font=font) if len(line) > 60: h += height * 2 else: h += height # Draw date & time draw.text((img.size[0] / 10, img.size[1] - font.size * 2), date, fill=theme[1], font=font) draw.text((img.size[0] / 10, img.size[1] - font.size * 3), time, fill=theme[1], font=font) # # Draw matermark waterdraw.text((img.size[0] / 10, img.size[1] / round(7)), "big mitya is watching you", font=watermark_font) watermask = watermark.convert("L").point(lambda x: min(x, 4)) watermark.putalpha(watermask) # img.paste(avatar, (int(img.size[0] / 25), 200), avatar) img.paste(watermark, None, watermark) path: str = "cit.png" img.save(path) return path
def draw_on(f, im): pil = to_pil(im) draw = ImageDraw.ImageDraw(pil) f(draw) return from_pil(pil)
def __init__(self, **kwargs): super().__init__(**kwargs) # import gltraces # mglprocs = mgl.glprocs(self.ctx) # gltraces.glprocs[:] = mglprocs # mglprocs[:] = gltraces.gltraces self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; out vec3 v_vert; out vec3 v_norm; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; } ''', fragment_shader=''' #version 330 uniform samplerCube Sampler; uniform vec3 Eye; in vec3 v_vert; in vec3 v_norm; out vec4 f_color; void main() { f_color = texture(Sampler, reflect(v_vert - Eye, v_norm)); } ''', ) img1 = Image.new('RGB', (200, 200), '#fee') img2 = Image.new('RGB', (200, 200), '#efe') img3 = Image.new('RGB', (200, 200), '#eef') img4 = Image.new('RGB', (200, 200), '#ffe') img5 = Image.new('RGB', (200, 200), '#fef') img6 = Image.new('RGB', (200, 200), '#eff') ImageDraw.ImageDraw(img1).text((50, 30), 'i1', '#000', ImageFont.truetype('arial', 128)) ImageDraw.ImageDraw(img2).text((50, 30), 'i2', '#000', ImageFont.truetype('arial', 128)) ImageDraw.ImageDraw(img3).text((50, 30), 'i3', '#000', ImageFont.truetype('arial', 128)) ImageDraw.ImageDraw(img4).text((50, 30), 'i4', '#000', ImageFont.truetype('arial', 128)) ImageDraw.ImageDraw(img5).text((50, 30), 'i5', '#000', ImageFont.truetype('arial', 128)) ImageDraw.ImageDraw(img6).text((50, 30), 'i6', '#000', ImageFont.truetype('arial', 128)) def join(*images): return b''.join(img.tobytes('raw', 'RGB', 0, -1) for img in images) self.texture = self.ctx.texture_cube((200, 200), 3, join(img1, img2, img3, img4, img5, img6)) self.sampler = self.ctx.sampler(self.texture) self.sampler.filter = mgl.LINEAR self.sampler.use() obj = Obj.open(data.find('sitting_dummy.obj')) self.vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz')) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, 'in_vert', 'in_norm') self.scope = self.ctx.scope(mgl.DEPTH_TEST)
def create_ocr_image(image: Path, page_context: PageContext): """Create the image we send for OCR. May not be the same as the display image depending on preprocessing. This image will never be shown to the user.""" output_file = page_context.get_path('ocr.png') options = page_context.options with Image.open(image) as im: white = ImageColor.getcolor('#ffffff', im.mode) # pink = ImageColor.getcolor('#ff0080', im.mode) draw = ImageDraw.ImageDraw(im) log.debug('resolution %r', im.info['dpi']) if not options.force_ocr: # Do not mask text areas when forcing OCR, because we need to OCR # all text areas mask = None # Exclude both visible and invisible text from OCR if options.redo_ocr: mask = True # Mask visible text, but not invisible text for textarea in page_context.pageinfo.get_textareas(visible=mask, corrupt=None): # Calculate resolution based on the image size and page dimensions # without regard whatever resolution is in pageinfo (may differ or # be None) bbox = [float(v) for v in textarea] xyscale = tuple( float(coord) / 72.0 for coord in im.info['dpi']) pixcoords = [ bbox[0] * xyscale[0], im.height - bbox[3] * xyscale[1], bbox[2] * xyscale[0], im.height - bbox[1] * xyscale[1], ] pixcoords = [int(round(c)) for c in pixcoords] log.debug('blanking %r', pixcoords) draw.rectangle(pixcoords, fill=white) # draw.rectangle(pixcoords, outline=pink) if options.threshold: pix = leptonica.Pix.frompil(im) pix = pix.masked_threshold_on_background_norm() im_pix = pix.topil() im_pix.info['dpi'] = im.info['dpi'] im = im_pix del draw filter_im = page_context.plugin_manager.hook.filter_ocr_image( page=page_context, image=im) if filter_im is not None: im = filter_im # Pillow requires integer DPI dpi = tuple(round(coord) for coord in im.info['dpi']) if page_context.pageinfo.rotation != 0: log.info(f"Rotating {page_context.pageinfo.rotation}") im = im.rotate(page_context.pageinfo.rotation) im.save(output_file, dpi=dpi) return output_file
def _test_font(self, font): im = Image.new('RGB', (255, 255), 'white') draw = ImageDraw.ImageDraw(im) self._test_leak(lambda: draw.text((0, 0), "some text "*1024, # ~10k font=font, fill="black"))
from PIL import Image, ImageDraw, ImageFont for infile in sys.argv[1:]: outfile = os.path.splitext( infile)[0] + ".text_watermark_website_by_python.jpeg" if infile != outfile: try: im = Image.open(infile) width, height = im.size # Create a new image for the watermark with an alpha layer (RGBA) # the same size as the original image watermark = Image.new("RGBA", im.size) # Get an ImageDraw object so we can draw on the image font = ImageFont.truetype('arial', 40) waterdraw = ImageDraw.ImageDraw(watermark, "RGBA") # Place the text at (10, 10) in the upper left corner. Text will be white. waterdraw.text((25, height - 60), "www.steadylearner.com", font=font) # Get the watermark image as grayscale and fade the image # See <http://www.pythonware.com/library/pil/handbook/image.htm#Image.point> # for information on the point() function # Note that the second parameter we give to the min function determines # how faded the image will be. That number is in the range [0, 256], # where 0 is black and 256 is white. A good value for fading our white # text is in the range [100, 200]. watermask = watermark.convert("L").point(lambda x: min(x, 195)) # Apply this mask to the watermark image, using the alpha filter to # make it transparent
img = img.unsqueeze(0) img = img.permute(0, 3, 1, 2) img = img.cuda() out_value = detector(img, 0.6, cfg.ANCHORS_GROUP) boxes = [] for j in range(4): classify_mask = (out_value[..., -1] == j) _boxes = out_value[classify_mask] boxes.append(tool.nms(_boxes.cpu())) for boxs in boxes: for box in boxs: try: img_draw = draw.ImageDraw(img1) # confidence = round(box[0].item(),2) c, x1, y1, x2, y2, cls = box[0:6] print(c.item(), x1.item(), y1.item(), x2.item(), y2.item()) x_1 = min(max(x1, 0), 416) # 在416的图像框上的坐标 y_1 = min(max(y1, 0), 416) x_2 = min(max(x2, 0), 416) y_2 = min(max(y2, 0), 416) # print(x_1, y_1, x_2, y_2) xx_1 = x_1 * max(im1.size[0], im1.size[1]) / 416 # 还原坐标 yy_1 = y_1 * max(im1.size[0], im1.size[1]) / 416 xx_2 = x_2 * max(im1.size[0], im1.size[1]) / 416
def get_image_from_sprite(m_Sprite) -> Image.Image: atlas = None if getattr(m_Sprite, "m_SpriteAtlas", None): atlas = m_Sprite.m_SpriteAtlas.read() elif getattr(m_Sprite, "m_AtlasTags", None): # looks like the direct pointer is empty, let's try to find the Atlas via its name for obj in m_Sprite.assets_file.objects.values(): if obj.type == ClassIDType.SpriteAtlas: atlas = obj.read() if atlas.name == m_Sprite.m_AtlasTags[0]: break atlas = None if atlas: sprite_atlas_data = atlas.m_RenderDataMap[m_Sprite.m_RenderDataKey] else: sprite_atlas_data = m_Sprite.m_RD m_Texture2D = sprite_atlas_data.texture alpha_texture = sprite_atlas_data.alphaTexture texture_rect = sprite_atlas_data.textureRect settings_raw = sprite_atlas_data.settingsRaw original_image = get_image(m_Sprite, m_Texture2D, alpha_texture) sprite_image = original_image.crop(( texture_rect.x, texture_rect.y, texture_rect.x + texture_rect.width, texture_rect.y + texture_rect.height, )) if settings_raw.packed == 1: rotation = settings_raw.packingRotation if rotation == SpritePackingRotation.kSPRFlipHorizontal: sprite_image = sprite_image.transpose(Image.FLIP_TOP_BOTTOM) # spriteImage = RotateFlip(RotateFlipType.RotateNoneFlipX) elif rotation == SpritePackingRotation.kSPRFlipVertical: sprite_image = sprite_image.transpose(Image.FLIP_LEFT_RIGHT) # spriteImage.RotateFlip(RotateFlipType.RotateNoneFlipY) elif rotation == SpritePackingRotation.kSPRRotate180: sprite_image = sprite_image.transpose(Image.ROTATE_180) # spriteImage.RotateFlip(RotateFlipType.Rotate180FlipNone) elif rotation == SpritePackingRotation.kSPRRotate90: sprite_image = sprite_image.transpose(Image.ROTATE_270) # spriteImage.RotateFlip(RotateFlipType.Rotate270FlipNone) if settings_raw.packingMode == SpritePackingMode.kSPMTight: # Tight # create mask to keep only the polygon mask = Image.new("1", sprite_image.size, color=0) draw = ImageDraw.ImageDraw(mask) for triangle in get_triangles(m_Sprite): draw.polygon(triangle, fill=1) # apply the mask if sprite_image.mode == "RGBA": # the image already has an alpha channel, # so we have to use composite to keep it empty_img = Image.new(sprite_image.mode, sprite_image.size, color=0) sprite_image = Image.composite(sprite_image, empty_img, mask) else: # add mask as alpha-channel to keep the polygon clean sprite_image.putalpha(mask) return sprite_image.transpose(Image.FLIP_TOP_BOTTOM)
if return_distance: return pixels_2d, if_visible, distance_ return pixels_2d, if_visible if __name__ == '__main__': from PIL import Image, ImageDraw name_ = 'n02814533_11997.JPEG' anno_path = '../PASCAL3D/annotations/car/' converter = MeshConverter() pixels, visibile, distance = converter.get_one(np.load(os.path.join(anno_path, name_.split('.')[0] + '.npz'), allow_pickle=True), return_distance=True) image = Image.open('../PASCAL3D/images/car/' + name_) imd = ImageDraw.ImageDraw(image) for p, v in zip(pixels, visibile): if v: color = (255, 0, 0) else: color = (0, 0, 255) box = bbt.box_by_shape((5, 5), p) imd.ellipse(box.pillow_bbox(), fill=color) image.show() image = Image.open('../PASCAL3D/images/car/' + name_) imd = ImageDraw.ImageDraw(image)
def test_images(self): model = get_detnet(input_shape=(self.image_height, self.image_width, self.image_channel), num_class=self.num_classes) get_local_max = NMS() ckpt_path = os.path.join(self.output_model_folder, "cp-{epoch:04d}.ckpt") # 可以使用str.format latest_ckpt = tf.train.latest_checkpoint(os.path.dirname(ckpt_path)) if latest_ckpt: start_epoch = int( os.path.basename(latest_ckpt).split('-')[1].split('.')[0]) model.load_weights(latest_ckpt) print('model resumed from: {}, start at epoch: {}'.format( latest_ckpt, start_epoch)) else: print('ERR: passing resume since weights not there') return 0 annotations = [] with open(self.annotation_file, 'r') as f: for line in f: items = line.strip().split(',') usage = int(items[0]) if usage == 1: continue # 训练集数据 image_path = os.path.join(self.image_root, items[1].strip()) annotations.append((image_path, items[2:])) print("images in dataset: {}".format(len(annotations))) for k in range(3): path_img, objs = random.choice(annotations) img = Image.open(path_img) data = np.array(img, dtype=np.uint8) data = tf.image.convert_image_dtype(data, tf.float32) data = tf.reshape(data, (1, self.image_height, self.image_width, -1)) hm_pred, wh_pred = model.predict(data) hm_pred = tf.sigmoid(hm_pred) # vis = hm_pred.numpy()[0,:,:,0] * 255 # plt.imshow(vis.astype(np.uint8),cmap='gray#') # plt.show() mask_max = get_local_max(hm_pred) bboxes = [] for cls in range(hm_pred.shape[-1]): for y in range(hm_pred.shape[1]): for x in range(hm_pred.shape[2]): prob = hm_pred[0, y, x, cls].numpy() if prob < 0.1: continue if mask_max[0, y, x, cls] == False: continue w, h = wh_pred[0, y, x, 0], wh_pred[0, y, x, 1] bboxes.append((x - w // 2, y - h // 2, x + w // 2, y + h // 2, prob)) if len(bboxes) > 10: bboxes = sorted(bboxes, key=lambda x: x[-1], reverse=True)[0:10] draw = ImageDraw.ImageDraw(img) for (x0, y0, x1, y1, _) in bboxes: x0, x1 = int(x0 * self.down_ratio), int(x1 * self.down_ratio) y0, y1 = int(y0 * self.down_ratio), int(y1 * self.down_ratio) draw.rectangle((x0, y0, x1, y1), outline="Red", width=3) plt.imshow(np.asarray(img, dtype=np.uint8)) plt.show()
def test_mode_mismatch(): im = hopper("RGB").copy() with pytest.raises(ValueError): ImageDraw.ImageDraw(im, mode="L")
def pathfinder(): """ Executes the game """ print("Creating universe") width, height, depth = 800, 800, 3 graph = nx.DiGraph() universe = np.zeros((width, height, depth), dtype=np.uint8) wall_factor = .01 star = np.array([255, 255, 255], dtype=np.uint8) print("My god, it's full of stars!") for _ in range(int((width * height) * wall_factor)): universe[np.random.randint(width)][np.random.randint(height)] = star print("Creating origin planet") starting_star_h, starting_star_w = np.random.randint(height), \ np.random.randint(width) print("Creating target planet") target_star_h, target_star_w = np.random.randint(height), \ np.random.randint(width) print("Contracting universe for FTL travel") reduction = np.mean(universe, axis=-1, dtype=np.int8) print("Mapping observable and void universe") for node_height, node_width in np.argwhere(reduction != -1): graph.add_node(str(node_height) + '|' + str(node_width)) if node_width + 1 < width: if reduction[node_height][node_width + 1] == 0: graph.add_edge( str(node_height) + '|' + str(node_width), str(node_height) + '|' + str(node_width + 1)) if node_height + 1 < height: if reduction[node_height + 1][node_width] == 0: graph.add_edge( str(node_height) + '|' + str(node_width), str(node_height + 1) + '|' + str(node_width)) if node_width - 1 > width: if reduction[node_height][node_width - 1] == 0: graph.add_edge( str(node_height) + '|' + str(node_width), str(node_height) + '|' + str(node_width - 1)) if node_height - 1 > height: if reduction[node_height - 1][node_width] == 0: graph.add_edge( str(node_height) + '|' + str(node_width), str(node_height - 1) + '|' + str(node_width)) if node_height - 1 > height and node_width - 1 > width: if reduction[node_height - 1][node_width - 1] == 0: graph.add_edge( str(node_height) + '|' + str(node_width), str(node_height - 1) + '|' + str(node_width - 1)) if node_height + 1 < height and node_width + 1 < width: if reduction[node_height + 1][node_width + 1] == 0: graph.add_edge( str(node_height) + '|' + str(node_width), str(node_height + 1) + '|' + str(node_width + 1)) if node_height + 1 < height and node_width - 1 > width: if reduction[node_height + 1][node_width - 1] == 0: graph.add_edge( str(node_height) + '|' + str(node_width), str(node_height + 1) + '|' + str(node_width - 1)) if node_height - 1 > height and node_width + 1 < width: if reduction[node_height - 1][node_width + 1] == 0: graph.add_edge( str(node_height) + '|' + str(node_width), str(node_height - 1) + '|' + str(node_width + 1)) print("Universe mapped. Found {} traversable spaces and {} paths".format( graph.number_of_nodes(), graph.number_of_edges())) try: print("Finding best path") points = [ list(map(int, visited.split('|'))) for visited in nx.algorithms.astar_path( graph, str(starting_star_h) + '|' + str(starting_star_w), str(target_star_h) + '|' + str(target_star_w)) ] except nx.exception.NetworkXNoPath: print( "The worlds are not on the same space-time grid. Try another parallel reality." ) sys.exit() print("Travelling! FTL speed reached") for point in points: universe[point[0]][point[1]] = [143, 188, 150] print("We achieved target planet. Generating report.") universe_picture = Image.fromarray(universe) draw = ImageDraw.ImageDraw(universe_picture) draw.ellipse((starting_star_w - 20, starting_star_h - 20, starting_star_w, starting_star_h), fill=(244, 167, 66)) draw.ellipse( (target_star_w - 20, target_star_h - 20, target_star_w, target_star_h), fill=(66, 86, 244)) del draw universe_picture.save('galaxy.png') print("Report generated. Exploration initiated.")
last_checked = time.time() # Main loop while True: # Limit calls to Dark Sky to 1 per minute if time.time() - last_checked > 60: weather_icon = get_weather_icon(get_weather(coords)) last_checked = time.time() # Load in the background image background = Image.open("images/weather.png").convert(oled.mode) # Place the weather icon and draw the background if weather_icon: background.paste(weather_icon, (10, 46)) draw = ImageDraw.ImageDraw(background) # Gets temp. and press. and keeps track of daily min and max temp if sensor.get_sensor_data(): temp = sensor.data.temperature press = sensor.data.pressure if datetime.datetime.today().day == curr_date: if temp < low_temp: low_temp = temp elif temp > high_temp: high_temp = temp else: curr_date = datetime.datetime.today().day low_temp = temp high_temp = temp
def pil_image(self, pp_args={}, watermark=None, width=None, height=None, crop=None, rotate=0): img = Image.fromarray(self.raw_img.postprocess(**pp_args)) if rotate != 0 or crop is not None: if crop is None: crop = [0, 0, 100, 100] w, h = img.size left = (crop[0] / 100.0) t = (crop[1] / 100.0) r = (crop[2] / 100.0) b = (crop[3] / 100.0) A = float(rotate) A = math.fabs(math.radians(A)) c = math.cos(A) s = math.sin(A) sx = left * w sy = t * h dx = (1.0 - r) * w dy = (1.0 - b) * h crop_ = (int(sx), int(sy), int(w - dx), int(h - dy)) img = img.crop(crop_) w, h = img.size new_w = (h * s + w * c) new_h = (h * c + w * s) scale = min(w / new_w, h / new_h) d_w = ((w * (1 - scale)) / 2.0) d_h = ((h * (1 - scale)) / 2.0) scale_crop = (int(d_w), int(d_h), int(w - d_w), int(h - d_h)) img = img.rotate(-float(rotate)).crop(scale_crop) if width is not None or height is not None: w, h = img.size if width is None: scale = float(height) / float(h) width = scale * float(w) if height is None: scale = float(width) / float(w) height = scale * float(h) height = int(height) width = int(width) img = img.resize((width, height), LANCZOS) if watermark is not None: mark = Image.new("RGBA", img.size) draw = ImageDraw.ImageDraw(mark, "RGBA") weight = img.size[0] // 40 offset = weight / 3 font = ImageFont.truetype( './pentaprism/webapp/static/style/Comfortaa-Regular.ttf', weight) fs = font.getsize(watermark) dx = (img.size[0] - fs[0]) - offset dy = (img.size[1] - fs[1]) - offset draw.text((dx, dy), watermark, font=font) mask = mark.convert("L").point(lambda x: min(x, 100)) mark.putalpha(mask) img.paste(mark, None, mark) return img
def _drawRotatedString(self, s, x, y, font=None, color=None, angle=0): # we depend on PIL for rotated strings so watch for changes in PIL try: import rdkit.sping.PIL.pidPIL from PIL import Image, ImageTk pp = rdkit.sping.PIL.pidPIL except ImportError: raise ImportError("Rotated strings only possible with PIL support") pilCan = pp.PILCanvas(size=(self.width, self.height)) pilCan.defaultFont = self.defaultFont pilCan.defaultLineColor = self.defaultLineColor if '\n' in s or '\r' in s: self.drawMultiLineString(s, x, y, font, color, angle) return if not font: font = pilCan.defaultFont if not color: color = self.defaultLineColor if color == rdkit.sping.pid.transparent: return # draw into an offscreen Image tempsize = pilCan.stringWidth(s, font) * 1.2 tempimg = Image.new('RGB', (tempsize, tempsize), (0, 0, 0)) txtimg = Image.new('RGB', (tempsize, tempsize), (255, 255, 255)) from PIL import ImageDraw temppen = ImageDraw.ImageDraw(tempimg) temppen.setink((255, 255, 255)) pilfont = pp._pilFont(font) if not pilfont: raise ValueError("Bad font: %s" % font) temppen.setfont(pilfont) pos = [4, int(tempsize / 2 - pilCan.fontAscent(font)) - pilCan.fontDescent(font)] temppen.text(pos, s) pos[1] = int(tempsize / 2) # rotate if angle: from math import pi, sin, cos tempimg = tempimg.rotate(angle, Image.BILINEAR) temppen = ImageDraw.ImageDraw(tempimg) radians = -angle * pi / 180.0 r = tempsize / 2 - pos[0] pos[0] = int(tempsize / 2 - r * cos(radians)) pos[1] = int(pos[1] - r * sin(radians)) ###temppen.rectangle( (pos[0],pos[1],pos[0]+2,pos[1]+2) ) # PATCH for debugging # colorize, and copy it in mask = tempimg.convert('L').point(lambda c: c) temppen.setink((color.red * 255, color.green * 255, color.blue * 255)) temppen.setfill(1) temppen.rectangle((0, 0, tempsize, tempsize)) txtimg.paste(tempimg, (0, 0), mask) ##Based on code posted by John Michelson in the PIL SIG transp = txtimg.convert("RGBA") source = transp.split() R, G, B, A = 0, 1, 2, 3 mask = transp.point(lambda i: i < 255 and 255) # use white as transparent source[A].paste(mask) transp = Image.merge(transp.mode, source) # build a new multiband image self.drawImage(transp, x - pos[0], y - pos[1])
from PIL import Image, ImageOps, ImageDraw from os import listdir from os.path import join import os img_dir = "./input/" out_dir = "./output/" img_filename = listdir(img_dir) img_full_dir = [join(img_dir, x) for x in listdir(img_dir)] for name, path in zip(img_filename, img_full_dir): img = Image.open(path) a = ImageDraw.ImageDraw(img) a.rectangle((285 // 4, 150 // 4, 410 // 4, 275 // 4), fill=None, outline='red', width=2) # img.show() img.save(join(out_dir, "rectangel_" + name)) #图片左上角为坐标原点 #水平为x,垂直为y #参数为x1,y1,x2,y2
for x, y in data_generator_from_hdf(conf): x = np.squeeze(x) image = np.transpose(x, (1, 2, 0)) image = np.asarray(image * 255, np.uint8) heatmap, limb, crop_size = y[0][0], y[1][0], y[2][0] max_pair, predicted_joints = inference_joints(heatmap, limb) joints_list = pair_joint_to_person( max_pair, predicted_joints, '{},{},{},{}'.format(crop_size[0], crop_size[1], crop_size[2], crop_size[3])) base = np.zeros( (crop_size[3] - crop_size[1], crop_size[2] - crop_size[0]), dtype=np.uint8) base = Image.fromarray(base) base_draw = ImageDraw.ImageDraw(base) for joints in joints_list: for joint in joints: joint = joints[joint] if joint is None: continue base_draw.ellipse((joint[0] - 10, joint[1] - 10, joint[0] + 10, joint[1] + 10), fill='white') base = base / np.max(base) plt.subplot(2, 4, 1) plt.imshow(image) plt.subplot(2, 4, 2) plt.imshow(image_list_blend(image, [base])) plt.subplot(2, 4, 3)
def __init__(self, **kwargs): super().__init__(**kwargs) # import gltraces # mglprocs = mgl.glprocs(self.ctx) # gltraces.glprocs[:] = mglprocs # mglprocs[:] = gltraces.gltraces self.prog = self.ctx.program( vertex_shader=''' #version 330 in vec2 in_vert; in vec3 in_text; out vec3 v_text; void main() { gl_Position = vec4(in_vert, 0.0, 1.0); v_text = in_text; } ''', fragment_shader=''' #version 330 uniform sampler2DArray Sampler; in vec3 v_text; out vec4 f_color; void main() { f_color = texture(Sampler, v_text); } ''', ) vertices = np.array([ rect(-0.5, -0.5, 0.9, 0.9, 0.0), rect(-0.5, 0.5, 0.9, 0.9, 1.0), rect(0.5, -0.5, 0.9, 0.9, 2.0), rect(0.5, 0.5, 0.9, 0.9, 3.0), ]) img1 = Image.new('RGB', (200, 200), '#fee') img2 = Image.new('RGB', (200, 200), '#efe') img3 = Image.new('RGB', (200, 200), '#eef') img4 = Image.new('RGB', (200, 200), '#ffe') ImageDraw.ImageDraw(img1).text((10, 10), 'img 1', '#000', ImageFont.truetype('arial', 32)) ImageDraw.ImageDraw(img2).text((10, 10), 'img 2', '#000', ImageFont.truetype('arial', 32)) ImageDraw.ImageDraw(img3).text((10, 10), 'img 3', '#000', ImageFont.truetype('arial', 32)) ImageDraw.ImageDraw(img4).text((10, 10), 'img 4', '#000', ImageFont.truetype('arial', 32)) def join(*images): return b''.join(img.tobytes('raw', 'RGB', 0, -1) for img in images) self.texture = self.ctx.texture_array((200, 200, 4), 3, join(img1, img2, img3, img4)) self.sampler = self.ctx.sampler(self.texture) self.sampler.use() self.vbo = self.ctx.buffer(vertices.astype('f4').tobytes()) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, 'in_vert', 'in_text')