def _save_custom(self, scale=5, format="pdf"): self._figure.filename = "._tmp_model_fig.svg" self._figure.stroke(width=scale * 1.25) self._save() self._figure.stroke(width=1) self._figure.filename = self.filename import os try: from svglib.svglib import svg2rlg except: print("Error: svglib not found (required for {} export)".format( format)) print("try 'pip install svglib'") os.remove("._tmp_model_fig.svg") return drawing = svg2rlg("._tmp_model_fig.svg") drawing.scale(scale, scale) drawing.width = self._width * scale drawing.height = self._height * scale if format is "pdf": from reportlab.graphics import renderPDF renderPDF.drawToFile(drawing, self.filename) if format is "png": from reportlab.graphics import renderPM renderPM.drawToFile(drawing, self.filename, fmt="PNG") os.remove("._tmp_model_fig.svg")
def process_image(filename): initialPalette = copy.deepcopy(self.image.palette) self.image.set_background(self.image.palette[bg]) self.image.compute_pixels() legend = False black_white = False if self.legend.get() == 1: legend = True else: legend = False if self.black_white.get() == 1: black_white = True else: black_white = False pattern = Pattern("_temp.svg", self.image, black_white, legend, 10) pattern.make_pattern() pattern.write() drawing = svg2rlg('_temp.svg') if export == "PDF": if not (filename[-4:] == ".pdf"): filename += ".pdf" renderPDF.drawToFile(drawing, filename, " ") if export == "PNG": if not (filename[-4:] == ".png"): filename += ".png" renderPM.drawToFile(drawing, filename, fmt='PNG') os.remove("_temp.svg") self.completion["text"] = f"Saved pattern as {filename}" self.confirm["state"] = "normal" self.image.palette = initialPalette
def ttf_ocr(font, key=None): gs = font.getGlyphSet() keys = [key for key in gs.keys() if key.startswith("uni")] if key is None else [key] c = [] for i, key in enumerate(keys): if key not in gs: logger.info("No this key: %s" % key) c.append("") continue pen = ReportLabPen(gs, Path(fillColor=colors.black, strokeWidth=0.01)) g = gs[key] g.draw(pen) w, h = 50, 50 g = Group(pen.path) g.translate(10, 10) g.scale(0.02, 0.02) d = Drawing(w, h) d.add(g) renderPM.drawToFile(d, png_file.name, fmt="PNG") result = os.popen("tesseract %s stdout -l chi_sim -psm 5" % png_file.name).read().strip().decode("utf-8", "ignore") if len(result) != 1: result = os.popen("tesseract %s stdout -l chi_sim -psm 8" % png_file.name).read().strip().decode("utf-8", "ignore") logger.info("key: %s, result: %s" % (key, result)) c.append(result) if key is not None: return c[0] return c
def render_video(self, start, end, title, skip_conversion): # Render video from frames with options outVidName = self.rootDir + title + ".mp4" if start < 1 or end > self.max_frame: print("frame out of bound") # TODO: add popup.show_warning() function so a warning with the above message can be called return # if skip_conversion is not true, each svg will be converted first to a png. if not skip_conversion: for i in range(start, end + 1): drawing = svg2rlg(self.folder_path + "/frame%d.svg" % i) renderPM.drawToFile(drawing, self.folder_path + "/frame%d.png" % i, fmt="PNG") # we create a dictionary storing all the image file names images = {} for img in os.listdir(self.folder_path): if img.endswith(".png"): file_num = int(re.sub("[^0-9]", "", img)) if start <= file_num <= end: images[file_num] = img fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V') video = cv2.VideoWriter(outVidName, fourcc, 15, (int(self.vid_width), int(self.vid_height)), True) for key, image in sorted(images.items()): video.write(cv2.imread(os.path.join(self.folder_path, image))) cv2.destroyAllWindows() video.release() self.show_image()
def post_main_tweet(board): text = header_msgs[state] peek = board.peek() if len(board.move_stack) > 0 else None arrow = [] if state != "new_game": if lastmove_text: text = text + "\nLast move chosen: " + lastmove_text if len(board.move_stack) >= 2: m = board.move_stack[-2] if board.turn == chess.WHITE else peek arrow = [(m.from_square, m.to_square)] if m else arrow # generate board image img_path = "chess.png" with open("chess.svg", "w") as f: f.write(chess.svg.board(board=board, lastmove=peek, arrows=arrow, size=400)) renderPM.drawToFile(svg2rlg("chess.svg"), img_path, fmt="PNG") media_id = upload_image(img_path) if not media_id: panic_clean_tweets() tweet_id = post_tweet(text, media_id=media_id) if not tweet_id: panic_clean_tweets() return tweet_id
def extract_stroke_path_from_svg(svg_name, svg_path, stroke_path): # 1. load svg file doc = minidom.parse(svg_path) # 2. get path path_elems = [p for p in doc.getElementsByTagName("path")] num_paths = int(len(path_elems) / 3) path_objs = [] for i in range(num_paths): path_objs.append(path_elems[i]) print("path len: ", len(path_objs)) # 3. save path to svg file for i in range(len(path_objs)): p_obj = path_objs[i] d = p_obj.getAttribute('d') content = '<svg version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <g transform="scale(1, -1) translate(0, -900)"><path d="' + d + \ '" fill="black"></path></g></svg>' with open( os.path.join(stroke_path, (svg_name + "_" + str(i) + ".svg")), 'w') as f: f.write(content) drawing = svg2rlg( os.path.join(stroke_path, (svg_name + "_" + str(i) + ".svg"))) renderPM.drawToFile( drawing, os.path.join(stroke_path, (svg_name + "_" + str(i) + ".png")), "png")
def pred_dep(sample_sentence): import keras import numpy as np import en_core_web_sm from PIL import Image from pathlib import Path from spacy import displacy nlp = en_core_web_sm.load() from svglib.svglib import svg2rlg from reportlab.graphics import renderPM svg = displacy.render(nlp(sample_sentence), style="dep", jupyter=False) Path("sample_sentence.svg").open("w", encoding="utf-8").write(svg) renderPM.drawToFile(svg2rlg("sample_sentence.svg"), "sample_sentence.png", fmt="PNG") im = Image.open("sample_sentence.png").convert('L').resize((1000, 200)) sample_image = np.array([np.array(im)]) sample_image = sample_image.reshape(sample_image.shape[0], sample_image.shape[1], sample_image.shape[2], 1) model = keras.models.load_model("dep_resnet.hdf5") y_pred = model.predict(sample_image) labels = [ "alcohol_and_drugs", "engagement", "neutral", "positive", "self_harm___harm_to_others", "vulnerability" ] return labels[np.argmax(y_pred)]
def do2(self, fig=None, **kwargs): from lxml import etree from reportlab.graphics import renderPM from svglib.svglib import SvgRenderer w, h, s = self.width, self.height, self.scale svg = fig.to_image(format="svg", width=w, height=h, scale=s * self.upscale) root = etree.fromstring(svg.decode("utf-8")) if root is None: raise Exception("Error while converting Plotly graphic.") svgRenderer = SvgRenderer("my.svg") drawing = svgRenderer.render(root) buf = io.BytesIO() renderPM.drawToFile(drawing, buf, fmt="PNG") buf.seek(0) _bytes = np.asarray(bytearray(buf.read()), dtype=np.uint8) img = cv2.imdecode(_bytes, cv2.IMREAD_COLOR) _w = int((int(root.get("width")) / self.upscale)) _h = int((int(root.get("height")) / self.upscale)) img = cv2.resize(img, (_w, _h), interpolation=cv2.INTER_AREA) return img
def preview(self, page, filelike, format="png", dpi=72, background_colour=0xFFFFFF): """Render a preview image of a page. Parameters ---------- page: positive integer Which page to render. Must be in the range [1, page_count] filelike: path or file-like object Can be a filename as a string, a Python file object, or something which behaves like a Python file object. For example, if you were using the Django web framework, an HttpResponse object could be passed to render the preview to the browser (as long as you remember to set the mimetype of the response). If you pass a filename, the existing contents will be overwritten. format: string The image format to use for the preview. ReportLab uses the Python Imaging Library (PIL) internally, so any PIL format should be supported. dpi: positive real The dots-per-inch to use when rendering. background_colour: Hex colour specification What color background to use. Notes ----- If you are creating this sheet for a preview only, you can pass the pages_to_draw parameter to the constructor to avoid the drawing function being called for all the labels on pages you'll never look at. If you preview a page you did not tell the sheet to draw, you will get a blank image. Raises ------ ValueError: If the page number is not valid. """ # Check the page number. if page < 1 or page > self.page_count: raise ValueError("Invalid page number; should be between 1 and {0:d}.".format(self.page_count)) # Shade any remaining missing labels if desired. self._shade_remaining_missing() # Rendering to an image (as opposed to a PDF) requires any background # to have an integer width and height if it is a ReportLab Image # object. Drawing objects are exempt from this. oldw, oldh = None, None if isinstance(self._bgimage, Image): oldw, oldh = self._bgimage.width, self._bgimage.height self._bgimage.width = int(oldw) + 1 self._bgimage.height = int(oldh) + 1 # Let ReportLab do the heavy lifting. renderPM.drawToFile(self._pages[page - 1], filelike, format, dpi, background_colour) # Restore the size of the background image if we changed it. if oldw: self._bgimage.width = oldw self._bgimage.height = oldh
def make_set_image_each_set(): """ Gets the svg for all sets from the api and converts it to png then saves both to disk. :param :return: """ sets = requests.get('https://api.scryfall.com/sets').json()['data'] small_sets = [] for set in sets: if set['released_at'] > '2015-01-01' and set[ 'released_at'] < '2019-05-01' and set['set_type'] in [ 'core', 'expansion' ]: small_sets.append(set) for set in small_sets: icon_uri = set['icon_svg_uri'] set_name_svg = '{}.svg'.format(set['code']) svg_location = 'svg_set_images' response_svg_image = requests.get(icon_uri) with open(os.path.join(svg_location, set_name_svg), "wb") as f: f.write(response_svg_image.content) drawing = svg2rlg(os.path.join(svg_location, set_name_svg)) renderPM.drawToFile(drawing, os.path.join('png_set_images', "{}.png".format(set['code'])), fmt="PNG")
def fmtbrd(board: chess.Board, color): flip = True if color == 'black' else False colors = { 'square dark': '#769656', 'sqaure light': '#eeeed2', 'arrow green': '#2a52be', 'arrow blue': '#2a52be', 'arrow red': '#2a52be', 'arrow yellow': '#2a52be' } try: last = board.peek().uci() arrows = [ chess.svg.Arrow(chess.parse_square(last[0:2]), chess.parse_square(last[2:4])) ] f = BytesIO( bytes(chess.svg.board(board, flipped=flip, colors=colors, arrows=arrows), encoding='utf-8')) except IndexError: f = BytesIO( bytes(chess.svg.board(board, flipped=flip, colors=colors), encoding='utf-8')) f.seek(0) new_f = BytesIO() drawing = svg2rlg(f) renderPM.drawToFile(drawing, new_f) new_f.seek(0) return discord.File(fp=new_f, filename='board.png')
def load_flag_image(country): """ download, reformat, load an image file as flag image from country image attribute :param country: Country object :return: None """ base_path = "images/images_flags/" if not os.path.isdir(os.path.join(base_path)): os.mkdir(os.path.join(base_path)) iso_code = str(country.alpha3_code).lower() file_name = iso_code + ".png" flag_url = country.flag if not os.path.isfile(os.path.join(base_path, file_name)): wget.download(flag_url, base_path) for file in os.listdir(base_path): if fnmatch.fnmatch(file, iso_code + ".svg"): file_png = file.split(".")[0] + ".png" svg_image = svg2rlg(base_path + file) try: renderPM.drawToFile(svg_image, base_path + file_png, fmt="PNG") except: file_png = "not_available.png" image = Image.open(base_path + file_png) image.thumbnail((200, 200)) image.save(base_path + file_png) os.remove(os.path.join(base_path, file)) return image else: for file in os.listdir(base_path): if fnmatch.fnmatch(file, iso_code + ".png"): image = Image.open(base_path + file) return image
def makeChord(root, chordType): #name = Chord Root #name = chord type getter = cList.loc[(cList['CHORD_ROOT'] == root) & (cList['CLASS'] == 'OPEN') & (cList['CHORD_TYPE'] == chordType) & (cList['ADVANCED_OR_NO'] == 'NOT_ADVANCED')] getter.head() pos = getter.iloc[0, 3].split(sep=",") fingers = getter.iloc[0, 6].split(sep=",") sFingers = "" sPos = "" for i in pos: sPos += i for j in fingers: if (j == "x"): j = "-" sFingers += j # print("Fingers",sFingers) # print("Positions",sPos) chord = fretboard.Chord(positions=sPos, fingers=sFingers) chord.save('temp.svg') # cairosvg.svg2png(url='temp.svg', write_to='temp.png') drawing = svg2rlg("temp.svg") # renderPDF.drawToFile(drawing, "file.pdf") renderPM.drawToFile(drawing, "temp.png", fmt="PNG")
def captcha_preprocessing(svg_data: str) -> np.array: """ Parsing SVG file body. remove useless element, save SVG as image :param svg_data: string with full svg data :return: image array """ tree = html.fromstring(svg_data) svg_elements = tree.xpath("//svg/path[@fill!='none']") svg_image = "" svg_image += """<svg xmlns="http://www.w3.org/2000/svg" width="150" height="50" viewBox="0,0,150,50">""" for element in svg_elements: svg_image += f"<path d='{element.attrib['d']}'></path>" svg_image += "</svg>" with BytesIO(bytes(svg_image, "utf-8")) as buf: buf.seek(0) # prepare and save image drawing = svg2rlg(buf) renderPM.drawToFile(drawing, buf, fmt="PNG") buf.seek(0) # procesing image to array image = np.asarray(bytearray(buf.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) return image
def captcha_builder_manual(resp): import PySimpleGUI as sg from PIL import Image from reportlab.graphics import renderPM from svglib.svglib import svg2rlg with open("captcha.svg", "w") as f: f.write(re.sub('(<path d=)(.*?)(fill="none"/>)', "", resp["captcha"])) drawing = svg2rlg("captcha.svg") renderPM.drawToFile(drawing, "captcha.png", fmt="PNG") im = Image.open("captcha.png") im = im.convert("RGB").convert("P", palette=Image.ADAPTIVE) im.save("captcha.gif") layout = [ [sg.Image("captcha.gif")], [sg.Text("Enter Captcha Below")], [sg.Input(key="input")], [sg.Button("Submit", bind_return_key=True)], ] window = sg.Window("Enter Captcha", layout, finalize=True) window.TKroot.focus_force() # focus on window window.Element("input").SetFocus() # focus on field event, values = window.read() window.close() return values["input"]
def captcha_downloader(): """ Download captcha for tests """ for _ in range(150): resp = requests.get( "https://mvd.gov.by/api/captcha/main?unique=1582836990084") data = resp.json()["data"] tree = html.fromstring(data) svg_elements = tree.xpath("//svg/path[@fill!='none']") svg_image = "" svg_image += ( """<svg xmlns="http://www.w3.org/2000/svg" width="150" height="50" viewBox="0,0,150,50">""" ) for element in svg_elements: svg_image += f"<path d='{element.attrib['d']}'></path>" svg_image += "</svg>" with BytesIO(bytes(svg_image, "utf-8")) as buf: buf.seek(0) drawing = svg2rlg(buf) renderPM.drawToFile(drawing, f"{PREPARED_FOLDER}{uuid4()}.png", fmt="PNG") time.sleep(0.9)
def resizeImage(infile, output_dir="resized"): outfile = os.path.splitext(infile)[0] + "" extension = os.path.splitext(infile)[1] if (infile != outfile and extension == ".svg" and infile != "croppedpicpp.PNG"): drawing = svg2rlg(infile) renderPM.drawToFile(drawing, "SVG" + os.path.splitext(infile)[0] + ".PNG") # if (infile != outfile and infile != "croppedpicpp.PNG" and extension != ".svg" and "SVG" in os.path.splitext(infile)[0]): try: size = (300, 300) im = Image.open(infile) imageW, imageH = im.size im.thumbnail(size, Image.ANTIALIAS) background = Image.new('RGBA', size, (255, 255, 255, 0)) background2 = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste(im, (int( (size[0] - im.size[0]) / 2), int((size[1] - im.size[1]) / 2))) background2.paste(background, (0, 0), background) #path = "C:/playground/images/main/resized" path = output_dir filename = os.path.join(path, outfile) background2.save(filename + outfile + ".PNG") #........................ except IOError: print("cannot reduce image for ", infile)
def test_captcha_builder_auto(api_key): from PIL import Image from svglib.svglib import svg2rlg from reportlab.graphics import renderPM from anticaptchaofficial.imagecaptcha import imagecaptcha import re, time drawing = svg2rlg('captcha.svg') renderPM.drawToFile(drawing, "captcha.png", fmt="PNG") solver = imagecaptcha() solver.set_verbose(1) solver.set_key(api_key) print("Started solving captcha...") tic = time.perf_counter() captcha_text = solver.solve_and_return_solution("captcha.png") toc = time.perf_counter() if captcha_text == "SNNvu": print(f"Captcha solve success: {captcha_text}") print(f"It took {toc - tic:0.4f} seconds to solve captcha") else: print( f"Task finished with error: {solver.error_code} - {captcha_text}") return captcha_text
def format_svg_base64(s: str) -> np.array: """ 格式化 svg 格式的 base64 图片字符串为模型需要的 8 * 8 的灰度数组,并返回展平成 1 维的数据 :param s: svg 格式的 base64 图片字符串 :return: np.array """ # base64 to svg with open('digit.svg', 'wb') as f: f.write(base64.b64decode(s)) # svg to png drawing = svg2rlg("digit.svg") renderPM.drawToFile(drawing, "digit.png", fmt="PNG") # 由于 png 的长宽并不规则,因此需要先将 png 压缩到能装入目标大小的尺寸 target_w, target_h = 8, 8 # 目标宽度和高度 png = Image.open('digit.png') w, h = png.size # 压缩前的宽和高 scale = min(target_w / w, target_h / h) # 确定压缩比例,保证缩小后到能装入 8 * 8 new_w, new_h = int(w * scale), int(h * scale) # 压缩后的宽和高 png = png.resize((new_w, new_h), Image.BILINEAR) # 压缩 # 将 png 复制粘贴到目标大小的空白底图中间,并用白色填充周围 new_png = Image.new('RGB', (target_w, target_h), (255, 255, 255)) # 新建空白底图 new_png.paste(png, ((target_w - new_w) // 2, (target_h - new_h) // 2)) # 复制粘贴到空白底图的中间 # 颜色反转(将手写的白底黑字,转变为模型需要的黑底白字),然后压缩数值到 0~16 的范围,并修改尺寸为 1 * 64 array = 255 - np.array(new_png.convert('L')) # 反转颜色 array = (array / 255) * 16 # 将数值大小压缩到 0~16 array = array.reshape(1, -1) # 修改尺寸为 1 * 64 return array
def process_svg_to_png_to_anin_gif(self): # self.subdir_svg = "./output_svg/" # self.subdir_png = "./output_png/" # self.subdir_anim_gif = "./output_anim_gif/" # n SVG -> n PNG print("Start converting SVG's to PNG ...") file_png_lst = [] for file_svg in self.file_svg_lst: filepath_svg = self.subdir_svg + file_svg file_png = file_svg[:-4] + ".png" file_png_lst.append(file_png) filepath_png = self.subdir_png + file_png drawing = svg2rlg(filepath_svg) renderPM.drawToFile(drawing, filepath_png, fmt="PNG") print("...ending converting SVG's to PNG ") # n PNG -> 1 anim GIF print("Start creating anim GIF from n PNG's ...") images = [] for file_png in file_png_lst: filepath_png = self.subdir_png + file_png file_gif = self.maze_name + "_anim.gif" filepath_gif = self.subdir_anim_gif + file_gif images.append(imageio.imread(filepath_png)) imageio.mimsave(filepath_gif, images) print("...ending creating anim GIF from n PNG's")
def preview(self, page, filelike, format='png', dpi=72, background_colour=0xFFFFFF): """Render a preview image of a page. Parameters ---------- page: positive integer Which page to render. Must be in the range [1, page_count] filelike: path or file-like object Can be a filename as a string, a Python file object, or something which behaves like a Python file object. For example, if you were using the Django web framework, an HttpResponse object could be passed to render the preview to the browser (as long as you remember to set the mimetype of the response). If you pass a filename, the existing contents will be overwritten. format: string The image format to use for the preview. ReportLab uses the Python Imaging Library (PIL) internally, so any PIL format should be supported. dpi: positive real The dots-per-inch to use when rendering. background_colour: Hex colour specification What color background to use. Notes ----- If you are creating this sheet for a preview only, you can pass the pages_to_draw parameter to the constructor to avoid the drawing function being called for all the labels on pages you'll never look at. If you preview a page you did not tell the sheet to draw, you will get a blank image. Raises ------ ValueError: If the page number is not valid. """ # Check the page number. if page < 1 or page > self.page_count: raise ValueError("Invalid page number; should be between 1 and {0:d}.".format(self.page_count)) # Shade any remaining missing labels if desired. self._shade_remaining_missing() # Rendering to an image (as opposed to a PDF) requires any background # to have an integer width and height if it is a ReportLab Image # object. Drawing objects are exempt from this. oldw, oldh = None, None if isinstance(self._bgimage, Image): oldw, oldh = self._bgimage.width, self._bgimage.height self._bgimage.width = int(oldw) + 1 self._bgimage.height = int(oldh) + 1 # Let ReportLab do the heavy lifting. renderPM.drawToFile(self._pages[page-1], filelike, format, dpi, background_colour) # Restore the size of the background image if we changed it. if oldw: self._bgimage.width = oldw self._bgimage.height = oldh
def svg_to_png(name): drawing = svg2rlg(name) try: renderPM.drawToFile(drawing, f"{name[:-4]}.png", fmt="PNG") return True except Exception: return False
def barChart(daten,Versuch,Phaenomene,path=None,vMin=1,vMax=6): """ Plots data to a Drawing and returns the Drawing """ #Festlegen der Gesamtgröße in Pixel d = Drawing(500,160) #Daten für das Diagramm #daten = [(10,6,8)] #Anlegen des Diagramms diagramm = HorizontalBarChart() #Positionierung und Größe des Diagramms diagramm.x = 10 diagramm.y = 30 diagramm.height = 100 diagramm.width = 400 #Hinzufügen der Daten #diagramm.reversePlotOrder = 1 diagramm.data = daten #Y-Achse (in ReportLab „valueAxis“) formatieren diagramm.valueAxis.valueMin = vMin diagramm.valueAxis.valueMax = vMax diagramm.valueAxis.valueStep = 1 #X-Achse (in ReportLab „categoryAxis“) formatieren diagramm.categoryAxis.categoryNames = Phaenomene #Diagramm zeichnen d.add(diagramm) if not path == None: Versuch = path + Versuch renderPM.drawToFile(d, Versuch + ".png", 'PNG') #d = Paragraph(d, centered) d.scale(0.8,0.8) return d
def designWithGraphEasy(): # v=1 sInput = ("design_schemes.txt") ''' sOutput = "design_schemes" + str(v) sOutput_html = "design_schemes" + str(v) + ".html") cmd1 = "graph-easy --input " + sInput + " > " + sOutput cmd2 = "graph-easy --as=ascii " + sInput + " > " + sOutput cmd3 = "graph-easy --as=boxart " + sInput + " > " + sOutput cmd4 = "graph-easy --as=html " + sInput + " > " + sOutput_html ''' cmd = ("graph-easy --as=svg " + sInput +" > design_schemes.svg") #print( cmd) # cmd2 = "graph-easy --as=ascii " + sInput + " > " + sOutput + ".txt") # print( cmd2 os.system(cmd) # os.system(cmd2) # convert img svg to PNG drawing = svg2rlg("design_schemes.svg") renderPM.drawToFile(drawing, "design_schemes.png", fmt="PNG")
def prepImage(file): ''' get .png image, if svg file specified then convert image to ong and apply skeletonization ''' from os import path img = np.zeros((HEIGHT, WIDTH)) if not path.isfile(file.split(".")[0] + ".png"): # given svg file, get a png file print("INFO : TARGET PNG IMAGE NOT FOUND, CREATING ...") from svglib.svglib import svg2rlg drawing = svg2rlg(file) from reportlab.graphics import renderPM renderPM.drawToFile(drawing, file.split(".")[0] + ".png", fmt="PNG") img = cv.imread(file.split(".")[0] + ".png", 0) # get GRAYSCALE image img = cv.resize(img, (100, 100), cv.INTER_CUBIC) # TODO : apply blur ex : medianBlur(img, 5) # load generated image and apply image transformations thresh = cv.THRESH_BINARY_INV _, img = cv.threshold( img, 0, 255, thresh + cv.THRESH_OTSU) # use otsu to find appropriate threshold img[np.where( img > 0)] = 1 # convert to image with 0's and 1's ex : binary image img = skeletonize( img, method="lee") # convert width of stroke to one pixel wide return img
def convert_svg_to_maze(svgFilename, outputFileName, maze_id): prs = Presentation(r'C:\Users\fjort\OneDrive\Documents\mazetplt.pptx') tmpPrsFile = r'C:\Users\fjort\PycharmProjects\maze\temp.pptx' tmpPDFFile = r'C:\Users\fjort\PycharmProjects\maze\tempPdf.pdf' sld = prs.slides[0] img = sld.shapes[0] # fpath = r'C:\Users\fjort\Downloads\maze.svg' # targetDir = r"C:\Users\fjort\Downloads" # # exportFile = os.path.join(targetDir, fpath[:-3]+"png") # print(exportPath) # Convert SVG to PNG drawing = svg2rlg(svgFilename) renderPM.drawToFile(drawing, outputFileName, fmt="PNG") # Replace maze in template replace_img_slide(sld, img, outputFileName) replace_text_slide(sld, maze_id, '') prs.save(tmpPrsFile) # Convert ppt to pdf convert_pptx_to_pdf(tmpPrsFile, tmpPDFFile) # Convert pdf to png convert_pdf_to_png(tmpPDFFile, outputFileName) print('Convert complete')
def _png(self, data, reportid): "PNG" if int(reportid) == 11: chart = build_barchart(data) elif int(reportid) == 9: chart = build_spam_chart(data) else: piedata = [getattr(row, REPORTS[reportid]['sort']) for row in data] total = sum(piedata) labels = [("%.1f%%" % ( (1.0 * getattr(row, REPORTS[reportid]['sort']) / total) * 100)) for row in data] chart = PieChart(350, 284) chart.chart.labels = labels chart.chart.data = piedata chart.chart.width = 200 chart.chart.height = 200 chart.chart.x = 90 chart.chart.y = 30 chart.chart.slices.strokeWidth = 1 chart.chart.slices.strokeColor = colors.black self.imgfile = StringIO() renderPM.drawToFile(chart, self.imgfile, 'PNG', bg=colors.HexColor('#FFFFFF'))
def test_captcha_builder(): from PIL import Image from svglib.svglib import svg2rlg from reportlab.graphics import renderPM import PySimpleGUI as sg drawing = svg2rlg('captcha.svg') renderPM.drawToFile(drawing, "captcha.png", fmt="PNG") im = Image.open('captcha.png') im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE) im.save('captcha.gif') layout = [[sg.Image('captcha.gif')], [sg.Text("Enter Captcha Below")], [sg.Input(key='input')], [sg.Button('Submit', bind_return_key=True)]] print("window opening ...") window = sg.Window('Enter Captcha', layout, finalize=True) window.TKroot.focus_force() # focus on window window.Element('input').SetFocus() # focus on field event, values = window.read() window.close() captcha_value = values['input'] expected_captcha_value = "SNNvu" if captcha_value == expected_captcha_value: print( "Yeah !!! you have entered captcha. This means you are all set to render required captcha at the time of booking ...\n" ) else: print( "\nOhh NO !!! you have entered wrong captcha : %s while expected: %s" % (captcha_value, expected_captcha_value)) print("Check if you are missing any required python packages\n\n")
def standardize_image_types(image_directory, img_size, grey_scale=False): img_list = listdir(image_directory) for img in tqdm(img_list): image = join(image_directory, img) image_present = True img_type = imghdr.what(image) if img_type == "webp": remove(image) image_present = False if img_type is None: try: drawing = svg2rlg(image) try: renderPM.drawToFile(drawing, image, fmt="PNG") remove(image) except ValueError: remove(image) image_present = False except AttributeError: remove(image) image_present = False except: remove(image) image_present = False if image_present: to_thumbnail(image, img_size)
def captcha_builder(resp): with open('captcha.svg', 'w') as f: f.write(re.sub('(<path d=)(.*?)(fill=\"none\"/>)', '', resp['captcha'])) drawing = svg2rlg('captcha.svg') renderPM.drawToFile(drawing, "captcha.png", fmt="PNG") #Seems like tkinter on my mac does not support PNG, convert it to GIF im = Image.open('captcha.png') im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE) im.save('captcha.gif') layout = [[sg.Image('captcha.gif')], [sg.Text("Enter Captcha Below")], [sg.Input(key='input')], [sg.Button('Submit', bind_return_key=True)]] window = sg.Window('Enter Captcha', layout, finalize=True) window.TKroot.focus_force() # focus on window window.Element('input').SetFocus() # focus on field event, values = window.read() window.close() print("================CAPTCHA %s========================" % values['input']) return values['input']
def convert_svg(file_name: str = "complex-3x3.svg", file_format: str = "pdf") -> None: """Method for converting the given svg file to a different file format Args: file_name: The name of the file to convert to pdf file_format: The type of file to output """ new_file_name = f"{file_name.split('.')[0]}.{file_format}" print(f"Attempting to convert {file_name} to {new_file_name}") file = open(f"{ROOT}/project/images/{file_name}", "r") drawing = svg2rlg(file) if file_format.lower() == "pdf": renderPDF.drawToFile(drawing, f"{ROOT}/project/images/{new_file_name}") else: renderPM.drawToFile(drawing, f"{ROOT}/project/images/{new_file_name}", fmt=file_format.upper()) file.close() print(f"Successfully converted {file_name} to {new_file_name}") return new_file_name
def _png(self, data, reportid): "PNG" if int(reportid) == 11: chart = build_barchart(data) elif int(reportid) == 9: chart = build_spam_chart(data) else: piedata = [getattr(row, REPORTS[reportid]['sort']) for row in data] total = sum(piedata) labels = [("%.1f%%" % ((1.0 * getattr(row, REPORTS[reportid]['sort']) / total) * 100)) for row in data] chart = PieChart(350, 284) chart.chart.labels = labels chart.chart.data = piedata chart.chart.width = 200 chart.chart.height = 200 chart.chart.x = 90 chart.chart.y = 30 chart.chart.slices.strokeWidth = 1 chart.chart.slices.strokeColor = colors.black self.imgfile = StringIO() renderPM.drawToFile(chart, self.imgfile, 'PNG', bg=colors.HexColor('#FFFFFF'))
def test_captcha_builder(): from PIL import Image from svglib.svglib import svg2rlg from reportlab.graphics import renderPM import PySimpleGUI as sg import re #with open('captcha.svg', 'w') as f: # f.write(re.sub('(<path d=)(.*?)(fill=\"none\"/>)', '', resp['captcha'])) drawing = svg2rlg('captcha.svg') renderPM.drawToFile(drawing, "captcha.png", fmt="PNG") im = Image.open('captcha.png') im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE) im.save('captcha.gif') layout = [[sg.Image('captcha.gif')], [sg.Text("Enter Captcha Below")], [sg.Input()], [sg.Button('Submit', bind_return_key=True)]] print("window opening ...") window = sg.Window('Enter Captcha', layout) event, values = window.read() window.close() captcha_value = values[1] expected_captcha_value = "SNNvu" if captcha_value == expected_captcha_value: print( "Yeah !!! you have entered captcha. This means you are all set to render required captcha at the time of booking ...\n" ) else: print( "\nOhh NO !!! you have entered wrong captcha : %s while expected: %s" % (captcha_value, expected_captcha_value)) print("Check if you are missing any required python packages\n\n")
def test_13_drawingRenderPNG(self): from reportlab.lib import colors from reportlab.graphics.shapes import Drawing, Rect from reportlab.graphics import renderPM d = Drawing(400,200) d.add(Rect(50,50,300,100, fillColor=colors.yellow)) renderPM.drawToFile(d, 'demo.jpg','JPG')
def generateversionchart((versionpickle, picklehash, imagedir, pickledir)): datapickle = open(os.path.join(pickledir, versionpickle), 'rb') data = cPickle.load(datapickle) datapickle.close() ## calculate the possible widths and heights of chart, bars, labels and so on maxversionstring = max(map(lambda x: len(x[0]), data)) barwidth = 15 chartwidth = len(data) * barwidth + 10 * len(data) maxvalue = max(map(lambda x: x[1], data)) step = int(math.log(maxvalue,10)) valueStep = pow(10,step) ## calculate a possible good value for startx and starty so labels are not cut off startx = max(10 + step * 10, 30) ## TODO: fiddle with values to create nicer looking graphs starty = maxversionstring * 10 + 20 drawheight = 225 + starty drawwidth = chartwidth + startx + 10 ## create the drawing drawing = Drawing(drawwidth, drawheight) bc = VerticalBarChart() bc.x = startx bc.y = starty bc.height = 200 bc.width = chartwidth bc.data = [tuple(map(lambda x: x[1], data))] bc.strokeColor = colors.white bc.valueAxis.valueMin = 0 bc.valueAxis.labels.fontSize = 16 bc.valueAxis.valueMax = maxvalue bc.valueAxis.valueStep = valueStep bc.categoryAxis.labels.boxAnchor = 'w' bc.categoryAxis.labels.dx = 0 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = -90 bc.categoryAxis.labels.fontSize = 16 bc.categoryAxis.categoryNames = map(lambda x: x[0], data) bc.barWidth = barwidth drawing.add(bc) outname = os.path.join(imagedir, picklehash) renderPM.drawToFile(drawing, outname, fmt='PNG') return picklehash
def chartBins(bins, filename): data = [] labels = [] keys = bins.keys() keys.sort() for k in keys: mid = (k[1] + k[0]) / 2.0 labels.append(str(mid)) data.append(len(bins[k])) maxval = max(data) data = [tuple(data)] # now, make the chart bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 500 bc.width = 1100 bc.data = data bc.valueAxis.valueMin = 0 bc.valueAxis.valueStep = 10 bc.valueAxis.valueMax = maxval + bc.valueAxis.valueStep bc.categoryAxis.labels.boxAnchor = "n" # bc.categoryAxis.labels.dx = 8 # bc.categoryAxis.labels.dy = -2 # bc.categoryAxis.labels.angle = 30 new_labels = [] for i, l in enumerate(labels): if i % 5 == 0: new_labels.append(l) else: new_labels.append("") # bc.categoryAxis.categoryNames = labels bc.categoryAxis.categoryNames = new_labels drawing = Drawing(1200, 600) drawing.add(bc) from reportlab.graphics import renderPM renderPM.drawToFile(drawing, output_filename)
def test_convert_pdf_png(self): """ Test converting W3C SVG files to PDF and PNG using svglib. ``renderPM.drawToFile()`` used in this test is known to trigger an error sometimes in reportlab which was fixed in reportlab 3.3.26. See https://github.com/deeplook/svglib/issues/47 """ exclude_list = [ "paint-stroke-06-t.svg", "coords-trans-09-t.svg", # renderPDF issue (div by 0) # Unsupported 'transform="ref(svg, ...)"' expression "coords-constr-201-t.svg", "coords-constr-202-t.svg", "coords-constr-203-t.svg", "coords-constr-204-t.svg", ] paths = glob.glob("%s/svg/*.svg" % self.folder_path) msg = "Destination folder '%s/svg' not found." % self.folder_path assert len(paths) > 0, msg for i, path in enumerate(paths): print("working on [%d] %s" % (i, path)) if basename(path) in exclude_list: print("excluded (to be tested later)") continue # convert drawing = svglib.svg2rlg(path) # save as PDF base = splitext(path)[0] + '-svglib.pdf' renderPDF.drawToFile(drawing, base, showBoundary=0) # save as PNG # (endless loop for file paint-stroke-06-t.svg) base = splitext(path)[0] + '-svglib.png' try: # Can trigger an error in reportlab < 3.3.26. renderPM.drawToFile(drawing, base, 'PNG') except TypeError: print('Svglib: Consider upgrading reportlab to version >= 3.3.26!') raise
def graph(self, nodeid=None): "Generate graphical system status" totals = DailyTotals(Session, c.user) if nodeid: server = self._get_server(nodeid) if not server: abort(404) baruwa_totals = totals.get(hostname=server.hostname) else: baruwa_totals = totals.get() if not baruwa_totals.total: abort(404) piedata = [] labels = [] for attr in ['clean', 'highspam', 'lowspam', 'virii', 'infected']: value = getattr(baruwa_totals, attr) or 0 piedata.append(value) if baruwa_totals.total > 0: labels.append(("%.1f%% %s" % ((1.0 * value / baruwa_totals.total) * 100, attr))) else: labels.append('0%') pie = PieChart(350, 264) pie.chart.labels = labels pie.chart.data = piedata pie.chart.width = 180 pie.chart.height = 180 pie.chart.x = 90 pie.chart.y = 30 pie.chart.slices.strokeWidth = 1 pie.chart.slices.strokeColor = colors.black pie.chart.slices[0].fillColor = PIE_CHART_COLORS[5] pie.chart.slices[1].fillColor = PIE_CHART_COLORS[0] pie.chart.slices[2].fillColor = PIE_CHART_COLORS[1] pie.chart.slices[3].fillColor = PIE_CHART_COLORS[9] pie.chart.slices[4].fillColor = PIE_CHART_COLORS[3] self.imgfile = StringIO() renderPM.drawToFile(pie, self.imgfile, 'PNG', bg=colors.HexColor('#ffffff')) response.content_type = 'image/png' response.headers['Cache-Control'] = 'max-age=0' return self.imgfile.getvalue()
def _preview(d,preview): '''create a device dependent preview image from drawing d''' from reportlab.graphics import renderPM if isinstance(preview,(int,float)): assert preview>0, "negative scaling is forbidden" g = d d = Drawing(g.width*preview, g.height*preview) g.transform = (preview,0,0,preview,0,0) #scale so it fits d.add(g) pilf = getBytesIO() transparent = getattr(g,'preview_transparent',None) or rl_config.eps_preview_transparent kwds = dict(fmt='TIFF') if transparent: configPIL = {} bg = configPIL['transparent'] = toColor(transparent) kwds['configPIL'] = configPIL kwds['bg'] = bg.int_rgb() renderPM.drawToFile(d,pilf,**kwds) return pilf.getvalue()
def _showDrawingDemo(self, drawing, name): """Show a graphical demo of the drawing.""" # Add the given drawing to the story. # Ignored if no GD rendering available # or the demo method does not return a drawing. try: from reportlab.graphics import renderPM modName = self.skeleton.getModuleName() path = '%s-%s.jpg' % (modName, name) renderPM.drawToFile(drawing, path, fmt='JPG') self.outLines.append('<H3>Demo</H3>') self.outLines.append(makeHtmlInlineImage(path)) except: if VERBOSE: print('caught exception in GraphHTMLDocBuilder._showDrawingDemo') traceback.print_exc() else: pass
def test0(self): "Test converting W3C SVG files to PDF using svglib." excludeList = [ "paint-stroke-06-t.svg", ] paths = glob.glob("%s/svg/*.svg" % self.folderPath) msg = "Destination folder '%s/svg' not found." % self.folderPath self.failUnless(len(paths) > 0, msg) for i, path in enumerate(paths): print "working on [%d]" % i, path if basename(path) in excludeList: print "excluded (to be tested later)" continue # convert try: drawing = svglib.svg2rlg(path) except: print "could not convert [%d]" % i, path continue # save as PDF base = splitext(path)[0] + '-svglib.pdf' try: renderPDF.drawToFile(drawing, base, showBoundary=0) except: print "could not save as PDF [%d]" % i, path # save as PNG # (endless loop for file paint-stroke-06-t.svg) base = splitext(path)[0] + '-svglib.png' try: renderPM.drawToFile(drawing, base, 'PNG') except: print "could not save as PNG [%d]" % i, path
def drawpie(arr,fname,depname): from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin from reportlab.lib.colors import Color, magenta, cyan from reportlab.graphics import renderPM class pietests(_DrawingEditorMixin,Drawing): def __init__(self,width=400,height=200,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,Pie(),name='pie',validate=None,desc=None) self.pie.sideLabels = 1 self.pie.labels = ['A', 'C', 'B', 'E','D','F','S'] self.pie.data = arr self.pie.width = 140 self.pie.height = 140 self.pie.y = 35 self.pie.x = 125 if __name__=="__main__": drawing = pietests() # you can do all sorts of things to drawing, lets just save it as pdf and png. #drawing.save(formats=['png'],outDir='./'+depname+'/'+fname,fnRoot=None) renderPM.drawToFile(drawing,'./'+depname+'/'+fname,fmt='GIF',configPIL={})
def _showWidgetDemo(self, widget): """Show a graphical demo of the widget.""" # Get a demo drawing from the widget and add it to the story. # Ignored if no GD rendering available # or the demo method does not return a drawing. try: from reportlab.graphics import renderPM drawing = widget.demo() if VERIFY: widget.verify() modName = self.skeleton.getModuleName() path = '%s-%s.jpg' % (modName, widget.__class__.__name__) renderPM.drawToFile(drawing, path, fmt='JPG') self.outLines.append('<H3>Demo</H3>') self.outLines.append(makeHtmlInlineImage(path)) except: if VERBOSE: print('caught exception in GraphHTMLDocBuilder._showWidgetDemo') traceback.print_exc() else: pass
def drawToFile(bc, filename): """Write barcode to PNG file <filename>.""" renderPM.drawToFile(barcode.rl.draw_barcode(bc), filename, 'PNG')
from fontTools.ttLib import TTFont from reportlab.lib import colors path = sys.argv[1] glyphName = sys.argv[2] if (len(sys.argv) > 3): imageFile = sys.argv[3] else: imageFile = "%s.png" % glyphName font = TTFont(path) # it would work just as well with fontTools.t1Lib.T1Font gs = font.getGlyphSet() pen = ReportLabPen(gs, Path(fillColor=colors.red, strokeWidth=5)) g = gs[glyphName] g.draw(pen) w, h = g.width, 1000 from reportlab.graphics import renderPM from reportlab.graphics.shapes import Group, Drawing, scale # Everything is wrapped in a group to allow transformations. g = Group(pen.path) g.translate(0, 200) g.scale(0.3, 0.3) d = Drawing(w, h) d.add(g) renderPM.drawToFile(d, imageFile, fmt="PNG")