def uploaded_file(filename): PATH_TO_TEST_IMAGES_DIR = app.config['UPLOAD_FOLDER'] TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, filename.format(i)) for i in range(1, 2) ] #IMAGE_SIZE = (12, 8) #parser = argparse.ArgumentParser(description='DeepNude App CLI Version with no Watermark.') #parser.add_argument('-i', "--input", help='Input image to process.', action="store", dest="input", required=False, default="input.jpg") #parser.add_argument('-o', "--output",help='Output path to save result.', action="store", dest="output", required=False, default="output.jpg") #parser.add_argument('-g', "--use-gpu", help='Enable using CUDA gpu to speed up the process.', action="store_true",dest="use_gpu", default=False) if not os.path.isdir("checkpoints"): print( "[-] Checkpoints folder not found, download it from Github repository, and extract files to 'checkpoints' folder." ) sys.exit(1) #arguments = parser.parse_args() #print("[*] Processing: %s" % arguments.input) #if (arguments.use_gpu): # print("[*] Using CUDA gpu to speed up the process.") for image_path in TEST_IMAGE_PATHS: #image = Image.open(image_path) dress = cv2.imread(image_path) h = dress.shape[0] w = dress.shape[1] dress = cv2.resize(dress, (512, 512), interpolation=cv2.INTER_CUBIC) watermark = process(dress) watermark = cv2.resize(watermark, (w, h), interpolation=cv2.INTER_CUBIC) cv2.imwrite('uploads/' + filename, watermark) return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
def deep_nude_process(dress): h = dress.shape[0] w = dress.shape[1] dress = cv2.resize(dress, (512, 512), interpolation=cv2.INTER_CUBIC) watermark = process(dress) watermark = cv2.resize(watermark, (w, h), interpolation=cv2.INTER_CUBIC) return watermark
def main(): dresses = [] for file in glob.glob('images/input/*'): filename = file[13:file.find('.')] print('Start converting: ' + file) if (os.path.exists('images/output/' + filename + '.png') and os.path.exists('images/concat/' + filename + '.png')): print('already converted') continue dress = cv2.imread(file) #Convert to png cv2.imwrite('images/input/' + filename + '.png', dress) #Read input image dress = cv2.imread('images/input/' + filename + '.png') #Process square, nude = process(dress) # Concat concat = cv2.hconcat([nude, square]) # Write output image cv2.imwrite('images/output/' + filename + '.png', nude) # Write output image cv2.imwrite('images/concat/' + filename + '.png', concat) #Exit sys.exit()
def _process(i_image, o_image, use_gpu): print("[*] Processing: %s" % use_gpu) try: dress = cv2.imread(i_image) h = dress.shape[0] w = dress.shape[1] dress = cv2.resize(dress, (512,512), interpolation=cv2.INTER_CUBIC) watermark = process(dress, use_gpu) watermark = cv2.resize(watermark, (w,h), interpolation=cv2.INTER_CUBIC) cv2.imwrite(o_image, watermark) print("[*] Image saved as: %s" % o_image) except Exception as ex: ex = str(ex) if "NoneType" in ex: print("[-] File %s not found" % i_image) elif "runtime error" in ex: print("[-] Error: CUDA Runtime not found, Disable the '--use-gpu' option!") else: print("[-] Error occured when trying to process the image: %s" % ex) with open("logs.txt", "a") as f: f.write("[-] Error: %s\n" % ex) sys.exit(1)
def process_one_image(i): result = process(image, gpu_ids, prefs) if args.overlay: result = utils.overlay_original_img( original_image, result, args.overlay[0], args.overlay[1], args.overlay[2], args.overlay[3]) cv2.imwrite(base_output_filename + "%03d.png" % i, result)
def deep_nude_process(item): print('Processing {}'.format(item)) dress = cv2.imread(item) h = dress.shape[0] w = dress.shape[1] dress = cv2.resize(dress, (512, 512), interpolation=cv2.INTER_CUBIC) watermark = process(dress) watermark = cv2.resize(watermark, (w, h), interpolation=cv2.INTER_CUBIC) return watermark
def main(i): #Read input image dress = cv2.imread("j" + str(i) + ".jpg") #Process watermark = process(dress) # Write output image cv2.imwrite("./out/oj" + str(i) + "out.jpg", watermark)
def main(): # Read input image dress = cv2.imread("input.png") # Process watermark = process(dress) # Write output image cv2.imwrite("output.png", watermark) # Exit sys.exit()
def main(): #Read input image dress = cv2.imread("input.png") #Process nude = process(dress) # Write output image cv2.imwrite("output.png", nude) #Exit sys.exit()
def main(): #Read input image dress = cv2.imread(sys.argv[1]) #Process watermark = process(dress) # Write output image cv2.imwrite(sys.argv[2], watermark) #Exit sys.exit()
def main(inputpath, outpath): dress = cv2.imread(inputpath) h = dress.shape[0] w = dress.shape[1] dress = cv2.resize(dress, (512, 512), interpolation=cv2.INTER_CUBIC) watermark = process(dress) watermark = cv2.resize(watermark, (w, h), interpolation=cv2.INTER_CUBIC) cv2.imwrite(outputpath, watermark)
def main(): #Read input image dress = cv2.imread("input2.jpg") h, w = dress.shape[:2] dress = cv2.resize(dress, (512, 512), interpolation=cv2.INTER_CUBIC) #Process watermark = process(dress) watermark = cv2.resize(watermark, (w, h), interpolation=cv2.INTER_CUBIC) # Write output image cv2.imwrite("output2.png", watermark) #Exit sys.exit()
def main(): start = time.time() gpu_ids = args.gpu if args.cpu: gpu_ids = None elif gpu_ids is None: gpu_ids = [0] if not args.gif: # Read input image image = cv2.imread(args.input) # Process result = process(image, gpu_ids, args.enablepubes) # Write output image cv2.imwrite(args.output, result) else: gif_imgs = imageio.mimread(args.input) nums = len(gif_imgs) print("Total {} frames in the gif!".format(nums)) tmp_dir = tempfile.mkdtemp() process_gif(gif_imgs, gpu_ids, args.enablepubes, tmp_dir) print("Creating gif") imageio.mimsave( args.output if args.output != "output.png" else "output.gif", [ imageio.imread(os.path.join( tmp_dir, "output_{}.jpg".format(i))) for i in range(nums) ], ) shutil.rmtree(tmp_dir) end = time.time() duration = end - start # Done print("Done! We have taken", round(duration, 2), "seconds") # Exit sys.exit()
def _process(self,i_image, o_image, use_gpu): try: try: dress=cv2.imdecode(np.fromfile(i_image,dtype=np.uint8),-1) except: dress = cv2.imread(i_image) h = dress.shape[0] w = dress.shape[1] dress = cv2.resize(dress, (512,512), interpolation=cv2.INTER_CUBIC) watermark = process(dress, use_gpu) watermark = cv2.resize(watermark, (w,h), interpolation=cv2.INTER_CUBIC) try: cv2.imencode('.png', watermark)[1].tofile(o_image) except: cv2.imwrite(o_image , watermark) print("[*] Image saved as: %s" % o_image) self.pbar.setValue(100) name=o_image if os.path.exists(name): self._tree.image=QPixmap(name) self._tree.graphicsView= QGraphicsScene() self._tree.item = QGraphicsPixmapItem(self._tree.image) self._tree.item.setFlag(QGraphicsItem.ItemIsMovable) # 使图元可以拖动,非常关键!!!!! self._tree.graphicsView.addItem(self._tree.item) #self._tree.setAlignment(Qt.AlignLeft and Qt.AlignTop) self._tree.setAlignment(Qt.AlignLeft) if self._tree.image.width()!=500: try: self._tree.item.setScale(500.0/self._tree.image.width()) except: pass self._tree.setScene(self._tree.graphicsView) self.box = QMessageBox(QMessageBox.Information, "提示", "转换成功!") self.box.addButton(u"确定", QMessageBox.YesRole).animateClick(1*1000) self.box.exec_() except Exception as e: print(e)
def _process(self,i_image, o_image, use_gpu): try: dress = cv2.imread(i_image) h = dress.shape[0] w = dress.shape[1] dress = cv2.resize(dress, (512,512), interpolation=cv2.INTER_CUBIC) watermark = process(dress, use_gpu) watermark = cv2.resize(watermark, (w,h), interpolation=cv2.INTER_CUBIC) cv2.imwrite(o_image, watermark) print("[*] Image saved as: %s" % o_image) self.pbar.setValue(100) name=o_image if os.path.exists(name): self._tree.image=QPixmap(name) self._tree.graphicsView= QGraphicsScene() self._tree.item = QGraphicsPixmapItem(self._tree.image) self._tree.graphicsView.addItem(self._tree.item) self._tree.setScene(self._tree.graphicsView) global image_name image_name=self._tree except Exception as e: print(e)
def main2(): dress = cv2.imread("input.png") watermark = process(dress) cv2.imwrite("output.png", watermark)
def main(args): if not os.path.isfile(args.input): print("Error : {} file doesn't exist".format(args.input), file=sys.stderr) exit(1) start = time.time() gpu_ids = args.gpu prefs = { "titsize": args.bsize, "aursize": args.asize, "nipsize": args.nsize, "vagsize": args.vsize, "hairsize": args.hsize } if args.cpu: gpu_ids = None elif gpu_ids is None: gpu_ids = [0] if not args.gif: # Read image file = open(args.input, "rb") image_bytes = bytearray(file.read()) np_image = np.asarray(image_bytes, dtype=np.uint8) image = cv2.imdecode(np_image, cv2.IMREAD_COLOR) # See if image loaded correctly if image is None: print("Error : {} file is not valid".format(args.input), file=sys.stderr) exit(1) # Preprocess if args.overlay: original_image = image.copy() image = utils.crop_input(image, args.overlay[0], args.overlay[1], args.overlay[2], args.overlay[3]) elif args.auto_resize: image = utils.resize_input(image) elif args.auto_resize_crop: image = utils.resize_crop_input(image) elif args.auto_rescale: image = utils.rescale_input(image) # See if image has the correct shape after preprocessing if image.shape != (512, 512, 3): print("Error : image is not 512 x 512, got shape: {}".format( image.shape), file=sys.stderr) exit(1) # Process if args.n_runs is None or args.n_runs == 1: result = process(image, gpu_ids, prefs) if args.overlay: result = utils.overlay_original_img(original_image, result, args.overlay[0], args.overlay[1], args.overlay[2], args.overlay[3]) cv2.imwrite(args.output, result) else: base_output_filename = utils.strip_file_extension( args.output, ".png") def process_one_image(i): result = process(image, gpu_ids, prefs) if args.overlay: result = utils.overlay_original_img( original_image, result, args.overlay[0], args.overlay[1], args.overlay[2], args.overlay[3]) cv2.imwrite(base_output_filename + "%03d.png" % i, result) if args.cpu: pool = ThreadPool(args.n_cores) pool.map(process_one_image, range(args.n_runs)) pool.close() pool.join() else: for i in range(args.n_runs): process_one_image(i) else: # Read images gif_imgs = imageio.mimread(args.input) print("Total {} frames in the gif!".format(len(gif_imgs))) # Preprocess if args.auto_resize: gif_imgs = [utils.resize_input(img) for img in gif_imgs] elif args.auto_resize_crop: gif_imgs = [utils.resize_crop_input(img) for img in gif_imgs] elif args.auto_rescale: gif_imgs = [utils.rescale_input(img) for img in gif_imgs] # Process if args.n_runs is None or args.n_runs == 1: process_gif_wrapper( gif_imgs, args.output if args.output != "output.png" else "output.gif", gpu_ids, prefs, args.n_cores) else: base_output_filename = utils.strip_file_extension( args.output, ".gif") if args.output != "output.png" else "output" for i in range(args.n_runs): process_gif_wrapper(gif_imgs, base_output_filename + "%03d.gif" % i, gpu_ids, prefs, args.n_cores) end = time.time() duration = end - start # Done print("Done! We have taken", round(duration, 2), "seconds") # Exit sys.exit()
"/")[-1] + "_bp_" + boundaries_param + "_lp_" + labels_param output_file = open(output_files_name + ".txt", "wb") # First, let's list all the available boundary algorithms output_file.write("Boundary methods: {}".format( msaf.get_all_boundary_algorithms())) # Let's check all the structural grouping (label) algorithms available output_file.write("\nLabeling methods: {}".format( msaf.get_all_label_algorithms())) # If available, you can use previously annotated boundaries and a specific labels algorithm # Set plot = True to plot the results # Try one of these boundary algorithms and print results boundaries, labels = run.process(audio_file, boundaries_id=boundaries_param, labels_id=labels_param) import datetime time_format = [ str(datetime.timedelta(seconds=int(elem))) for elem in boundaries ] boundaries = ["{:.3f}".format(elem) for elem in boundaries] # import pdb; pdb.set_trace() output_file.write("\n\nBoundaries: {}".format(boundaries)) output_file.write("\n\nTime Format: {}".format(time_format)) output_file.write("\n\nLabels: {}".format(labels))
for part in email_message.walk(): # this part comes from the snipped I don't understand yet... if part.get_content_maintype() == 'multipart': continue if part.get('Content-Disposition') is None: continue fileName = clean_file_name(part.get_filename()) # Do not download and parse same book multiple times if fileName in unique_books: continue else: unique_books.add(fileName) if bool(fileName) and 'csv' in fileName: fileName = fileName.replace('.csv', '') + f'___{sender_info}' + '.csv' filePath = os.path.join('../data', fileName) if not os.path.isfile(filePath): fp = open(filePath, 'wb') fp.write(part.get_payload(decode=True)) fp.close() subject = str(email_message).split("Subject: ", 1)[1].split("\nTo:", 1)[0] print('Downloaded : "{file}"'.format(file=fileName)) print('Parsing book...') process(filePath) print('\n' * 3)
def process(in_path, annot_beats=False, feature="mfcc", ds_name="*", framesync=False, boundaries_id="gt", labels_id=None, n_jobs=4, config=None): """Sweeps parameters across the specified algorithm.""" results_file = "results_sweep_boundsE%s_labelsE%s.csv" % (boundaries_id, labels_id) if labels_id == "cnmf3" or boundaries_id == "cnmf3": config = io.get_configuration(feature, annot_beats, framesync, boundaries_id, labels_id, algorithms) hh = range(8, 16) RR = range(8, 16) ranks = range(2, 4) RR_labels = range(11, 12) ranks_labels = range(6, 7) all_results = pd.DataFrame() for rank in ranks: for h in hh: for R in RR: for rank_labels in ranks_labels: for R_labels in RR_labels: config["h"] = h config["R"] = R config["rank"] = rank config["rank_labels"] = rank_labels config["R_labels"] = R_labels # Run process run.process(in_path, ds_name=ds_name, n_jobs=n_jobs, boundaries_id=boundaries_id, labels_id=labels_id, config=config) # Compute evaluations results = eval.process(in_path, boundaries_id, labels_id, ds_name, save=True, n_jobs=n_jobs, config=config) # Save avg results new_columns = { "config_h": h, "config_R": R, "config_rank": rank, "config_R_labels": R_labels, "config_rank_labels": rank_labels } results = results.append([new_columns], ignore_index=True) all_results = all_results.append(results.mean(), ignore_index=True) all_results.to_csv(results_file) elif labels_id is None and boundaries_id == "sf": config = io.get_configuration(feature, annot_beats, framesync, boundaries_id, labels_id, algorithms) MM = range(8, 24) mm = range(2, 4) kk = np.arange(0.02, 0.1, 0.01) Mpp = range(16, 24) ott = np.arange(0.02, 0.1, 0.01) all_results = pd.DataFrame() for M in MM: for m in mm: for k in kk: for Mp in Mpp: for ot in ott: config["M_gaussian"] = M config["m_embedded"] = m config["k_nearest"] = k config["Mp_adaptive"] = Mp config["offset_thres"] = ot # Run process run.process(in_path, ds_name=run_name, n_jobs=n_jobs, boundaries_id=boundaries_id, labels_id=labels_id, config=config) # Compute evaluations results = eval.process(in_path, boundaries_id, labels_id, ds_name, save=True, n_jobs=n_jobs, config=config) # Save avg results new_columns = { "config_M": M, "config_m": m, "config_k": k, "config_Mp": Mp, "config_ot": ot } results = results.append([new_columns], ignore_index=True) all_results = all_results.append(results.mean(), ignore_index=True) all_results.to_csv(results_file) else: logging.error("Can't sweep parameters for %s algorithm. " "Implement me! :D")
from run import process config_fname = '/storage/store2/data/erp-core/config_N400.py' process(config=config_fname, steps='preprocessing/make_epochs')
pdata.loc[grps[True], "pargp"] = "welflux" pdata.loc["ss", "parval1"] = ml.upw.ss.array.mean() pdata.loc["ss", "parubnd"] = ml.upw.ss.array.mean() * 10.0 pdata.loc["ss", "parlbnd"] = ml.upw.ss.array.mean() * 0.1 pdata.loc["ss", "pargp"] = "storage" pdata.loc["sy", "parval1"] = ml.upw.sy.array.mean() pdata.loc["sy", "parubnd"] = ml.upw.sy.array.mean() * 10.0 pdata.loc["sy", "parlbnd"] = ml.upw.sy.array.mean() * 0.1 pdata.loc["sy", "pargp"] = "storage" #apply obs weights and groups and values import run run.process() run.write_other_obs_ins() shutil.copy2(os.path.join("misc", "other.obs"), os.path.join("misc", "other.obs.truth")) smp = pyemu.pst_utils.smp_to_dataframe( os.path.join("misc", "freyberg_heads_truth.smp")) values = list(smp.loc[:, "value"]) pst.observation_data.loc[:, "weight"] = 0.0 pst.observation_data.loc[:, "obgnme"] = "forecast" groups = pst.observation_data.groupby( pst.observation_data.obsnme.apply(lambda x: x in obs_names)).groups pst.observation_data.loc[groups[True], "weight"] = 100.0 pst.observation_data.loc[groups[True], "obgnme"] = "head_cal" groups = pst.observation_data.groupby( pst.observation_data.obsnme.apply(lambda x: x.startswith('o'))).groups