def input_symptoms(): if request.method == 'POST': travel = str(request.form['travel']) tiredcough = str(request.form['commonsym']) breath = str(request.form['majorsym']) exposure = str(request.form['exposure']) try: image = request.files['image'] image.save('beach1.bmp') except: return render_template('index.html', results="No File Found") file_path = "beach1.bmp" # to load pre-saved model # test pathogen = predict_pathogen("./image.png", loaded_model) return render_template('index.html', results=result, result2=result2, pathogen=pathogen) return None
def runtests(opt, stream): """ Run *count* of tests, - images will be saved to the temp folder. Side comparison. """ for _ in range(0, opt.test): image1 = image.frombytes(stream.getimagebytes()) if opt.mask: image.mask(image1, opt.mask) time.sleep(opt.pause) image2 = image.frombytes(stream.getimagebytes()) if opt.mask: image.mask(image2, opt.mask) difference = image.diff(image1, image2) if difference >= opt.motionat: image.save( image.combine( image1, image2, "%s // %s" % (time.strftime("%Y-%m-%d %H:%M:%S"), difference) ), opt.storage ) logging.info("!! Motion detected: %s" % difference) else: logging.debug("No motion detected: %s" % difference)
def saveImage(multi=False): """Save an image to file. This will show the Save Image dialog, with the multisave mode checked if multi = True. Then, depending on the user's selection, it will either: - save the current Canvas/Window to file - start the multisave/autosave mode - do nothing """ pat = map(utils.fileDescription, ['img', 'icon', 'all']) dia = widgets.SaveImageDialog(pf.cfg['workdir'], pat, multi=multi) opt = dia.getResult() if opt: if opt.fm == 'From Extension': if utils.fileTypeFromExt(opt.fn) == '': opt.fn += '.png' opt.fm = None if opt.qu < 0: opt.qu = -1 updateSettings({'workdir': os.path.dirname(opt.fn)}, save=True) image.save(filename=opt.fn, format=opt.fm, quality=opt.qu, size=opt.sz, window=opt.wi, multi=opt.mu, hotkey=opt.hk, autosave=opt.au, border=opt.bo, rootcrop=opt.rc)
def saveImage(multi=False): """Save an image to file. This will show the Save Image dialog, with the multisave mode checked if multi = True. Then, depending on the user's selection, it will either: - save the current Canvas/Window to file - start the multisave/autosave mode - do nothing """ pat = map(utils.fileDescription, ['img','icon','all']) dia = widgets.SaveImageDialog(GD.cfg['workdir'],pat,multi=multi) opt = dia.getResult() if opt: if opt.fm == 'From Extension': opt.fm = None if opt.qu < 0: opt.qu = -1 updateSettings({'workdir':os.path.dirname(opt.fn)},save=True) image.save(filename=opt.fn, format=opt.fm, quality=opt.qu, window=opt.wi, multi=opt.mu, hotkey=opt.hk, autosave=opt.au, border=opt.bo, rootcrop=opt.rc )
def result(self, image_path, results, expected, compare=True): fullpath = path = os.path.abspath(os.path.join('data', image_path)) if self.resized_dir is not None: im = image.max_size(image.load(path), (320, 240)) path = os.path.join(self.resized_dir, os.path.basename(image_path)) print os.path.dirname(image_path) image.save(im, path) del im self.write('<tr>') self.write('<td rowspan="%(len)d"><a href="%(fullpath)s"><img src="%(path)s" width="320" /><br />%(imgpath)s</a></td>', fullpath=fullpath, path=path, imgpath=image_path, len=len(results)) for i,pair in enumerate(results.iteritems()): name,result = pair if i != 0: self.write("</tr><tr>") self.write('<td>%(name)s</td><td>%(score)r</td>', name=name, score=result[1]) self.write('<td class="%(cls)s">%(confirmed)s</td><td>%(expected)s</td>', cls="bad" if compare and result[2] != (name in expected) else "good", confirmed="Yes" if result[2] else "", expected="Yes" if name in expected else "") self.write('<td class="%(cls)s">%(timing).2f second(s)</td>', cls="bad" if compare and result[3] > 10 else "", timing=result[3]) self.write("</tr>")
def make_preview(trainer): with chainer.using_config('train', False): with chainer.no_backprop_mode(): x_a = iterator_a.next() x_a = convert.concat_examples(x_a, device) x_a = chainer.Variable(x_a) x_b = iterator_b.next() x_b = convert.concat_examples(x_b, device) x_b = chainer.Variable(x_b) x_ab = g_a(x_a) x_ba = g_b(x_b) x_bab = g_a(x_ba) x_aba = g_b(x_ab) preview_dir = '{}/preview'.format(dst) if not os.path.exists(preview_dir): os.makedirs(preview_dir) image_dir = '{}/image'.format(dst) if not os.path.exists(image_dir): os.makedirs(image_dir) names = ['a', 'ab', 'aba', 'b', 'ba', 'bab'] images = [x_a, x_ab, x_aba, x_b, x_ba, x_bab] for n, i in zip(names, images): i = cp.asnumpy(i.data)[:,:,padding:-padding,:].reshape(1, -1, 128) image.save(image_dir+'/{}{}.jpg'.format(trainer.updater.epoch,n), i) w = np.concatenate([gla.inverse(_i) for _i in dataset.reverse(i)]) dataset.save(preview_dir+'/{}{}.wav'.format(trainer.updater.epoch,n), 16000, w)
def _shade_render_save(normals: Tensor, svbrdf: SVBRDF, lights: List[Light], viewer: Viewer, camera: Camera, path: str) -> None: ''' Shades, renders, and saves a picture to the given path from the provided normals, Lights, Viewer, Camera, and SVBRDF. Args: normals: Tensor [1, R, C, 3] of normals to use for shading. svbrdf: SVBRDF to use for shading. lights: Lights to use for shading. viewer: Viewer to use for shading. camera: Camera to use for rendering. path: Path to use for saving the image. ''' num_rows, num_cols = normals.size(1), normals.size(2) num_size = max(num_rows, num_cols) surface = (utils.create_grid(num_rows=num_rows, num_cols=num_cols) - torch.tensor([0.5, 0.5, 0])) * torch.tensor( [num_cols / num_size, num_rows / num_size, 1]) radiance = shader.shade(surface=surface, normals=normals, lights=lights, viewer=viewer, svbrdf=svbrdf) picture = camera.render(surface=surface, radiance=radiance[0]) image.save(path=path, image=picture, encoding='sRGB')
def input_symptoms(): if request.method == 'POST': travel = str(request.form['travel']) tiredcough = str(request.form['commonsym']) breath = str(request.form['majorsym']) exposure = str(request.form['exposure']) try: # to load pre-saved model loaded_model = load_model() image = request.files['image'] image.save('temp_image.bmp') pathogen = predict_pathogen("./temp_image.bmp", loaded_model) current_labels = [ 'No Finding', 'Effusion', 'Infiltration', 'Atelectasis', 'Edema', 'Consolidation', 'Mass', 'Nodule', 'Fibrosis' ] pathogen = pathogen[0] sorted_lists = [ x for _, x in sorted(zip(pathogen, current_labels)) ] result_dict = dict(zip(current_labels, pathogen)) print(sorted_lists) filtered_list = [] top_two_results = sorted_lists[-2:] print(top_two_results) for condition in top_two_results: if condition in diag_info_dict.keys(): filtered_list.append( [condition, diag_info_dict[condition]]) else: filtered_list.append([condition, 'No additional info']) result = ','.join([travel, tiredcough, breath, exposure]) result2 = 'result 2' return render_template('index.html', results=result, result2=result2, pathogen=filtered_list) except: return render_template('index.html', results="No File Found")
def saveframe(frame, dest, filename, caption="DATE: %s | DIFF: %s | FRAME: %s", params=()): """ Save image with watermark. """ filename = str(filename) filename = filename.rjust(12, "0") image.watermark(frame, caption % params) image.save(frame, dest, filename)
def main(): filename = 'cat.png' image = Image.open(filename) size = width, height = image.size enchancer = ImageEnhance.Bightness(image) image = enchancer.enchance(0.5) image.save("modified_" + filename) del image
def input_symptoms(): if request.method == 'POST': try: travel = int(request.form['travel']) except: travel = 0 try: tiredcough = int(request.form['commonsym']) except: tiredcough = 0 try: breath = int(request.form['majorsym']) except: breath = 0 try: exposure = int(request.form['exposure']) except: exposure = 0 try: image = request.files['image'] image.save('beach1.bmp') except: return render_template('index.html', results="No File Found") file_path = "beach1.bmp" with open(file_path, "rb") as content_file: content = content_file.read() image = automl.Image(image_bytes=content) payload = automl.ExamplePayload(image=image) # params is additional domain-specific parameters. # score_threshold is used to filter the result # https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#predictrequest params = {"score_threshold": "0.8"} request2 = automl.PredictRequest(name=model_full_id, payload=payload, params=params) # 'content' is base-64-encoded image data. response = prediction_client.predict(request=request2) for result in response.payload: var1 = result.display_name var2 = result.classification result2 = 'Disease: ', var1, ' Probability of disease: ', var2 result = travel + tiredcough + breath + exposure if result >= 3: result = 'You have high chances of being covid positive' else: result = 'Please take care of yourself(wear a mask :D)' return render_template('index.html', results=result, result2=result2) return None
def on_btn_Save_Clicked(self): save_path = QFileDialog.getSaveFileName(self, "Save Your Paint", ".\\", "*.png") print(save_path) if save_path[0] == "": print("Save cancel") return image = self.__paintBoard.GetContentAsQImage() image.save(save_path[0]) print(save_path[0])
def compute_path_image(infilename, outfilename, start, end, threshold=10): '''Altera l'immagine nel file infilename colorando il percorso da start a end e salvandola nel file outfilename. Usa un grafo implicito.''' img = load(infilename) tree = visit_tree_image(img, start, end, threshold) path = visit_path(tree, end) draw_path(img, path) save(outfilename, img)
def upload(): if request.files['image'].filename != '': image = request.files['image'] file_path = './.tmp/{}'.format(image.filename) image.save(file_path) uploaded = bucket.upload(file_path, image.filename) if uploaded: return "uploaded" return abort(400) return abort(500)
def readfile(): """ read the config file and execute the command :return: nothing """ file = open("conf.txt", 'r') for line in file: isActive = line.split("=") isActive[1] = isActive[1] if line.find("input_dir=") >= 0 and isActive[1] != "\n": if line.find("= ") >= 0: command = line.split("= ") else: command = line.split("=") i.path = command[1].rstrip("\n") if line.find("output_dir=") >= 0 and isActive[1] != "\n": print(isActive[1] + "s") if line.find("= ") >= 0: command = line.split("= ") else: command = line.split("=") i.folder = command[1] if line.find("filters=") >= 0 and isActive[1] != "": i.dico = i.open_image() if line.find("= ") >= 0: command = line.split("= ") else: command = line.split("=") filtre = command[1].split("|") for c in filtre: if c == "grayscale": i.dico = i.nb() if c.find("blur") >= 0: sep = c.split(":") i.dico = i.blur(int(sep[1])) if c.find("dilate") >= 0: sep = c.split(":") i.dico = i.dilate(int(sep[1])) if c.find("FilterZeTeam") >= 0: i.dico = i.FilterZeTeam() i.save()
def compute_path(infilename, outfilename, start, end, threshold=10): '''Altera l'immagine nel file infilename colorando il percorso da start a end e salvandola nel file outfilename. Usa le funzioni load() e save() dal capitolo sulle immagini.''' img = load(infilename) g = image_to_graph(img, threshold) tree = visit_tree(g, start) path = visit_path(tree, end) draw_path(img, path) save(outfilename, img)
def f2i(path): DPI = 200 OUTPUT_FOLDER = None FIRST_PAGE = None LAST_PAGE = None FORMAT = 'jpg' THREAD_COUNT = 1 USERPWD = None USE_CROPBOX = False STRICT = False index = 0 # This method reads a pdf and converts it into a sequence of images # PDF_PATH sets the path to the PDF file # dpi parameter assists in adjusting the resolution of the image # output_folder parameter sets the path to the folder to which the PIL images can be stored (optional) # first_page parameter allows you to set a first page to be processed by pdftoppm # last_page parameter allows you to set a last page to be processed by pdftoppm # fmt parameter allows to set the format of pdftoppm conversion (PpmImageFile, TIFF) # thread_count parameter allows you to set how many thread will be used for conversion. # userpw parameter allows you to set a password to unlock the converted PDF # use_cropbox parameter allows you to use the crop box instead of the media box when converting # strict parameter allows you to catch pdftoppm syntax error with a custom type PDFSyntaxError # path_1 = os.getcwd() path_1 = os.path.join(os.getcwd(), 'images') try: os.makedirs(path_1, exist_ok=True) print("Directory '%s' created successfully" % path_1) except OSError as error: os.remove(path_1) os.makedirs(path_1) print("Directory deleted and created") images = [[]] start_time = time.time() dirs = os.listdir(path) # print(len(dirs)) for file in dirs: if file.endswith("pdf"): path1 = path + "/" + file pil_images = pdf2image.convert_from_path(path1, dpi=DPI, output_folder=OUTPUT_FOLDER, first_page=FIRST_PAGE, last_page=LAST_PAGE, fmt=FORMAT, thread_count=THREAD_COUNT, userpw=USERPWD, use_cropbox=USE_CROPBOX, strict=STRICT) # images.append(pil_images) print("Time taken : " + str(time.time() - start_time)) pathB = os.getcwd() os.chdir(path_1) # This method helps in converting the images in PIL Image file format to the required image format # for image in pil_images: for image in pil_images: image.save("page" + str(index) + ".jpg") index += 1 os.chdir(pathB)
def _extract_flow(config: Configuration) -> None: ''' The "extract" flow renders a flash-lit picture of a texture from the dataset. Args: config: Configuration specifying the parameters of the flow. ''' with torch.no_grad(): dataset, texture, output = config.load_extract_flow() material = dataset.textures.index(texture) batch, _ = dataset.sample(material) picture = batch[0, :3].permute(1, 2, 0) image.save(path=output, image=picture, encoding='sRGB')
def mosaic_average(fname_in, fname_out, s): '''Ritorna una nuova immagine ottenuta dividendo l'immagine img in quadrati di lato s e riempendo ogni quadratino con la media dei suoi colori.''' img = image.load(fname_in) w, h = len(img[0]), len(img) ret = image.create(w, h, (0,0,0)) # itera sui possibili quadrati for jj in range(h//s): for ii in range(w//s): # colore medio dell'immagine c = average(img,ii*s,jj*s,s,s) draw_quad(ret, ii*s, jj*s, s, s, c) image.save(fname_out, ret)
def mosaic_nearest(fname_in, fname_out, s): """Ritorna una nuova immagine ottenuta dividendo l'immagine img in quadrati di lato s e riempendo ogni quadrato con il colore del suo angolo in alto a sinistra""" img = image.load(fname_in) w, h = len(img[0]), len(img) ret = image.create(w, h, (0,0,0)) # itera sui possibili quadrati for jj in range(h//s): for ii in range(w//s): # colore dell'angolo in alto-sinistra c = img[jj*s][ii*s] draw_quad(ret, ii*s, jj*s, s, s, c) image.save(fname_out, ret)
def to_jpeg(self): new_basename_root, old_ext = \ os.path.splitext(os.path.basename(self.filename)) new_basename = new_basename_root + '.jpg' new_filename = tempfile.gettempdir() + os.path.sep + new_basename image = Image.open(self.filename) if image.mode != 'RGB': image = image.convert('RGB') image.save(new_filename, 'JPEG', quality=100) new_file = JPEGFile(new_filename) new_file.item = self.item new_file.index = self.index return new_file
def fit(input_path: str, output_path: str, optimizer: str, svbrdf: SVBRDF) -> None: ''' Fits the given SVBRDF to each material in the MERL 100 dataset using the provided hyperparameters. Args: input_path: Path to the MERL 100 BRDF slice image. output_path: Path to the desired output image. optimizer: SciPy optimizer to use to fit the SVBRDF. svbrdf: SVBRDF model to fit. ''' brdfs = _load_MERL_100_BRDF_slices(input_path) # It is known a priori that each BRDF slice has a width and height of 60 pixels. normals, incident_directions, outbound_directions = _generate_SVBRDF_directions( num_rows=60, num_cols=60) # There is a 10 pixel gap between each BRDF slice in a pair and a 30 pixel gap between BRDF slice pairs. comparison = torch.zeros(30 + 10 * 90, 30 + 10 * 160, 3) for i, want_brdf in tqdm.tqdm(enumerate(brdfs), desc='SVBRDF Optimization', total=100, disable=logging.root.level == logging.DEBUG): # Each SVBRDF parameter has a valid range of [0, 1]; however, the optimizers are bad at handling extremes. guess = torch.rand(svbrdf.depth).numpy() / 5 + 0.4 bounds = scipy.optimize.Bounds(numpy.array([0.01] * svbrdf.depth), numpy.array([0.99] * svbrdf.depth)) # Find an "optimal" set of parameters for the SVBRDF which minimizes the MSE loss with respect to the material BRDF slice. solution = scipy.optimize.minimize( fun=_evaluate_function, jac=_evaluate_gradient, x0=guess, args=(svbrdf, normals, incident_directions, outbound_directions, want_brdf), method=optimizer, bounds=bounds) logging.debug('Material %d was fit with an MSE loss of %.6f', i, solution.fun) # Compute the BRDF slice associated with the optimized parameters. svbrdf.parameters = torch.from_numpy(solution.x).expand( 1, normals.size(0), normals.size(1), -1) have_brdf = svbrdf(normals, incident_directions, outbound_directions).squeeze().clamp(0, 1) # Copy the MERL 100 BRDF slice alongside the optimized BRDF slice into the output image. row = 30 + 90 * (i // 10) col = 30 + 160 * (i % 10) comparison[row:row + 60, col:col + 60, :] = want_brdf comparison[row:row + 60, col + 70:col + 130, :] = have_brdf image.save(path=output_path, image=comparison, encoding='sRGB')
def polarize(fname_in, colors, fname_out): inputImage = im.load(fname_in) outputImage = [] for r in range(len(inputImage)): outputImageRow = [] for c in range(len(inputImage[0])): outputImageRow.append(ApproximateColor(inputImage[r][c], colors)) outputImage.append(outputImageRow) im.save(fname_out, outputImage)
def mosaic_size(fname_in, fname_out, s): '''Ritorna una nuova immagine ottenuta dividendo l'immagine img in quadratini di lato s e disegnando all'interno di ognuno di essi, su sfondo nero, un quadratino centrale bianco di lato proporzionale alla luminosità media del corrispondente quadratino''' img = image.load(fname_in) w, h = len(img[0]), len(img) ret = image.create(w, h, (0,0,0)) # itera sui possibili quadrati for jj in range(h//s): for ii in range(w//s): # colore medio dell'immagine c = average(img,ii*s,jj*s,s,s) # lato del quadratino bianco r = round(s*(c[0]+c[1]+c[2])/(3*255)) draw_quad(ret, ii*s+(s-r)//2, jj*s+(s-r)//2, r, r, (255,255,255)) image.save(fname_out, ret)
def fill(img_in, boundaries, pp_cc, img_out): '''Implementare qui la funzione''' img = image.load(img_in) w, h = len(img[0]), len(img) for pc in pp_cc: visited = set([pc[0]]) active = set([pc[0]]) while len(active) > 0: newactive = set() while len(active) > 0: x, y = active.pop() for dx, dy in ADJACENTS: px, py = x + dx, y + dy if px >= 0 and px < w and py >= 0 and py < h: if (px, py) not in boundaries: img[py][px] = pc[1] if (px, py) not in visited: visited.add((px, py)) newactive.add((px, py)) active = newactive image.save(img_out, img)
def copy_to_offscreen(self, image): global options, grabber, display # Convert a PIL Image to a gtk.gdk.Pixbuf if (platform.system() == 'Linux'): file1 = io.BytesIO() else: file1 = StringIO() if (file1 != False): image.save(file1, "ppm") contents = file1.getvalue() loader = gtk.gdk.PixbufLoader("pnm") loader.write(contents, len(contents)) pixbuf = loader.get_pixbuf() loader.close() file1.close() # copy Pixbuf to offscreen area/Pixbuf grabber.lock_offscreen.acquire() gtk.gdk.threads_enter() pixbuf.copy_area(0, 0, display.width, display.height, self.offscreen, 0, 0) # Report status if grabber.active: display.bartext.set_text("Recording") else: display.bartext.set_text("") # Force an 'expose' event for screen display.expose_event(display.drawing_area, None) gtk.gdk.threads_leave() grabber.lock_offscreen.release() return True
def _bakeAndSave(self, bake_type, out_name, cs): log.info(f' {self.obj.name} start {bake_type} bake ' f'(size={self.img.generated_width}, samples={self.samples})') self.img.colorspace_settings.name = cs bpy.context.scene.render.engine = 'CYCLES' bpy.context.scene.cycles.device = 'GPU' bpy.context.scene.cycles.samples = self.samples bpy.context.scene.cycles.use_denoising = True bpy.context.scene.cycles.bake_type = bake_type if bake_type == 'DIFFUSE': bpy.context.scene.render.bake.use_pass_direct = False bakeData = self.objData.setdefault('bake', {}).setdefault(bake_type, {}) bakeData['res'] = self.img.generated_width bakeData['samples'] = bpy.context.scene.cycles.samples self.obj.select_set(state=True) try: t1 = time.time() bpy.ops.object.bake('INVOKE_DEFAULT', type=bake_type, use_clear=True) bakeData['bake_time'] = round(time.time() - t1, 2) except Exception as err: log.warning(err) else: # these should be named by content since some will be the same (dup object under 2 lights will have some of the same maps) t2 = time.time() image.save( self.img, dest / f'stage/bake/render/{self.inst_name}/{self.obj.name}_{out_name}.png', logPrefix=' ') bakeData['save_time'] = round(time.time() - t2, 2)
def edging(fname_in, fname_out, n_iter): img = image.load(fname_in) width, height = len(img[0]), len(img) img_out = image.create(width, height, (0, 0, 0)) pix_hood = ((-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0)) for _ in range(n_iter): for row in range(height): for col in range(width): color = img[row][col] max_distance = 0 max_color = color for x, y in pix_hood: row_hood = y + row col_hood = x + col if not (0 <= col_hood < width and 0 <= row_hood < height): continue color_hood = img[row_hood][col_hood] distance = calc_dist(color, color_hood) if distance > max_distance: max_distance = distance max_color = color_hood img_out[row][col] = max_color img, img_out = img_out, img image.save(fname_out, img)
def save_spirals(training_set, output, filename, size, show, descriptor=None, drops=None): colors = [utils.hex_to_tuple(x[2]) for x in output[1]] image.save(positions=[(x[0], x[1]) for x in training_set], colors=[utils.hex_to_tuple(x[2]) for x in training_set], width=size, height=size, path=filename + "_original.png", show=show) image.save(positions=[(x[0], x[1]) for x in output[1]], colors=colors, width=size, height=size, path=filename + ".png", show=show) if descriptor != None: image.save(positions=descriptor, colors=[utils.hex_to_tuple("#00FF00") for x in descriptor], width=size, height=size, path=filename + "_descriptor.png", show=show) if drops != None: image.save(positions=drops, colors=[utils.hex_to_tuple("#FF0000") for x in drops], width=size, height=size, path=filename + "_drops.png", show=show)
def save_cover_art(release, max_retries=3): """Save the front cover image for the release `release`. Return the saved image's ID, or None if the image isn't available.""" if release['cover-art-archive']['front'] == 'false': return None for retry in range(max_retries): try: image_data = musicbrainzngs.get_image_front(release['id'], size="500") return image.save(image_data, 'catalog') except ResponseError as err: if err.cause.code == 404: # image doesn't exist break elif err.cause.code == 503: print('rate limit exceeded: retrying in {} seconds.'.format( RETRY_SECS)) time.sleep(RETRY_SECS) except NetworkError: break return None
def stopMultiSave(): """Stop multisave mode.""" image.save()
def save(self, filename): image.save(filename, self.to_img())
# """ RGB color image """ from scipy import misc import numpy as np import image as img class rgb_image(img.image): """ """ def __init__(self, w=0, h=0, fileName=None): """ Construction d'une image de width x height pixels contenant trois channels R,G et B """ if None == fileName: img.image.__init__(self, w, h, 3) else: data = misc.imread(fileName) img.image.__init__(self, data.shape[0], data.shape[1], 3) self.__pixels__ = data[:, :, 0:3] / 255. if __name__ == '__main__': img = rgb_image(fileName='lena_rgb.png') img.pixels = np.ones((img.height, img.width, 3), np.double) - img.pixels img.show() img.save("inverse_rgb_lena.png")
def main(conf): img = image.open(conf.file) segments = image.segment(img, int(conf.cluster), it=5) image.save('./output/' + str(time.time()), segments)
###################################### #### QR- CODE GENERATOR WITH PYTHON #### #### First install 2 modules in CMD #### -> qrcode -> pip install qrcode #### -> image -> pip install image #### ###################################### import qrcode import image qr = qrcode.QRCode( version= 15, # means the version of the qr code high the number bigger the code image and complicated pictuıre box_size=10, # size of the box where qe code will be displayed border= 5 # it is the white part of the image -- border in all 4 sides with white color ) data = "https://fatihes1.github.io/" # as I have given the path of my resume website # if you do not want to redirect and create for normal text that write text in the quotes qr.add_data(data) qr.make(fit=True) # The following lines of code will create your qr-code and save it in the same directory as your '.py' file image = qr.make_image(fill='black', back_color='white') image.save("qr_code.png")
def saveImage(image, target): try: image.save(target) except IOError: raise RuntimeError('Cannot write image file %s' % target)