def supresol(): inputName = request.form.to_dict()['fileName'] outputName = 'SR_' + inputName.split('.')[0] + '.jpg' # 원래 사진 파일 s3에서 다운로드 downloadFileFromS3('inputImage/superResolution/' + inputName, outputName) # super resolution 하기 # chanel 4 ->3 lr_img = Image.open(outputName).convert("RGB") lr_img_np = np.array(lr_img) print("...load RRDN-GAN...") sr_model = RRDN(weights='gans') sr_img_gan = sr_model.predict(lr_img_np) sr_img_gan = Image.fromarray(sr_img_gan) sr_img_gan.save(outputName) # 후처리된 사진 파일 s3에 업로드 (+서버에선 파일 지움) uploadFileToS3(outputName, 'outputImage/superResolution/' + outputName) os.remove(outputName) # 파일 다운로드 s3 링크 받아오기 url = getUrlFromS3('outputImage/superResolution/' + outputName) # 클라이언트로 링크 전송 return url
def predict_sr(filename): if request.method == 'POST': file_path = os.path.join(APP_ROOT, 'static/output') if not os.path.isdir(file_path): os.mkdir(file_path) img = Image.open(os.path.join('static/images/', filename)) #resize LR img.resize(size=(img.size[0] * 4, img.size[1] * 4), resample=Image.BICUBIC) #prediction lr_img = np.array(img) rrdn = RRDN(arch_params={ 'C': 4, 'D': 3, 'G': 32, 'G0': 32, 'x': 4, 'T': 10 }) rrdn.model.load_weights( 'weights/rrdn-C4-D3-G32-G032-T10-x4_epoch299.hdf5') sr_img = rrdn.predict(lr_img) Image.fromarray(sr_img) #save image sr = Image.fromarray(sr_img) sr.save(os.path.join(file_path, filename)) return render_template("result.html", prediction=filename)
def image_super_resolution(file_in_path, file_out_path): rdn = RDN(weights='noise-cancel') rrdn = RRDN(weights='gans') img = imread(file_in_path) lr_img = np.array(img) if lr_img.shape[0] >= 360 or lr_img.shape[1] >= 640: sr_img = rdn.predict(lr_img) else: sr_img = rrdn.predict(lr_img) imsave(file_out_path, sr_img)
def image_deblur(path, filename): img = Image.open(path) model = RRDN(weights='gans') # model = RDN(weights='psnr-small') # model = RDN(weights='psnr-large') # model = RDN(weights='noise-cancel') img.resize(size=(img.size[0] * 4, img.size[1] * 4), resample=Image.BICUBIC) sr_img = model.predict(np.array(img), by_patch_of_size=None, padding_size=2) new = Image.fromarray(sr_img) #output_stream = open(app.config['DOWNLOAD_FOLDER'] + filename, 'wb') tf.keras.backend.clear_session() #output.write(output_stream) new.save(DOWNLOAD_FOLDER + filename, 'JPEG')
def unblur(self, img = None, out = False): if(img == None): img = self.img_blur if(self.log): print('GANS work') model = RRDN(weights='gans') sr_img = model.predict(np.array(img)) if(self.log): print('Scale work') scale_percent = 25 width = int(sr_img.shape[1] * scale_percent / 100) height = int(sr_img.shape[0] * scale_percent / 100) sr_img = cv2.resize(sr_img, (width, height), interpolation = cv2.INTER_NEAREST) self.img_unblur = sr_img if(out): return sr_img
#print(os.getcwd()) if os.path.exists(temp_dir): print("exists") else: print("directory empty, make movie in low resolution first") #covert saved images to movie path_str = temp_dir + '/*.jpg' img_array = [] pathlist = glob.glob(path_str) pathlist.sort() #print(pathlist) #output size from ISR size = (image_size * 4, image_size * 4) out = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*'DIVX'), fps, size) for filename in pathlist: img = cv2.imread(filename) img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img_sr = rrdn.predict(img_rgb) out.write(img_sr) out.release() print("movie done") #remove temp directory #if os.path.exists(temp_dir): # shutil.rmtree(temp_dir)
def predict(img): lr_img = np.array(img) model = RRDN(weights='gans') sr_img = model.predict(np.array(lr_img)) return (Image.fromarray(sr_img))
def save_img(img: IMG, file_path: str): img.save(file_path) all_img_paths = get_all_img_paths('../image_2') outdir = 'output_isr/' os.makedirs(outdir, exist_ok=True) for i, img_path in enumerate(all_img_paths): try: org_file_name = os.path.basename(img_path)[::-1].replace('.', '__', 1)[::-1] print('processing {}[{}/{}]'.format(org_file_name, i + 1, len(all_img_paths))) img = Image.open(img_path, mode='r') img = img.convert('RGB') img = resize_lr_img(img) img = denoise(img) save_img(img, outdir + "{}_{}.png".format(org_file_name, 'org')) print(img.size) lr_img_array = np.array(img) print('predict with srresnet') sr_img_rdn = Image.fromarray(rdn.predict(lr_img_array)) save_img((sr_img_rdn), outdir + "{}_{}.png".format(org_file_name, 'srr')) print('predict with srgam') sr_img_rrdn = Image.fromarray(rrdn.predict(lr_img_array)) save_img(sr_img_rrdn, outdir + "{}_{}.png".format(org_file_name, 'srg')) save_img(combine_image_horizontally([img, sr_img_rdn, sr_img_rrdn]), outdir + '{}_com.png'.format(org_file_name)) except Exception as e: print(e)
import numpy as np from PIL import Image img = Image.open('data/DIV2K_train_LR_x8/0009x8.png') lr_img = np.array(img) from ISR.models import RRDN rrdn = RRDN(arch_params={'C': 4, 'D': 3, 'G': 64, 'G0': 64, 'T': 10, 'x': 2}) rrdn.model.load_weights('rrdn_90_500_16_valPSNR_Y.hdf5') sr_img = rrdn.predict(lr_img) tmp = Image.fromarray(sr_img) tmp.save("test2.jpg")
# Create two folders named as "LR_images" and "SR_images" # Put all the low resolution images in LR_images folder and then use GANS to # convert it into High Resolution # Put all converted images into SR_images folder #import GANs model from ISR.models import RRDN #load the pretrained weights - (Trained on DIV2K dataset) model = RRDN(weights='gans') files = [img for img in glob.glob("LR_images/*.jpg")] d=1 for im in files: img = Image.open(im) sr_img = model.predict(np.array(img)) Image.fromarray(sr_img).save("SR_images/%d.jpg"%d) d+=1 # Regular expression and validation of aadhar no. def regex(text): uid = set() newlist = [] for xx in text.split('\n'): newlist.append(xx) newlist = list(filter(lambda x: len(x) > 12, newlist)) for no in newlist: if re.match("^[0-9 ]+$", no): uid.add(no) if(len(list(uid))>=1): # Validating using Verhoeff algorithm
from PIL import Image from ISR.models import RDN, RRDN # Import the image img = Image.open('input.png') # Load the GAN model that will perform a 4x resize model = RRDN(weights='gans') # Convert to numpy image npimg = np.array(img) row,col,ch= npimg.shape # Add some noise mean = 0 var = 0.1 sigma = var**0.5 gauss = np.random.normal(mean,sigma,(row,col,ch))*24 # Reshape and clip the pixel values gauss = gauss.reshape(row,col,ch) noisy = np.clip(npimg + gauss, 0, 255).astype('uint8') noisy_image = Image.fromarray(noisy) # Do the resize big_np = model.predict(np.array(noisy_image)) # Save the image big_img = Image.fromarray(big_np) big_img.save("big.jpg")
img.resize(size=(img.size[0]*4, img.size[1]*4), resample=Image.BICUBIC) #prediction 1 sr_img1 = model1.predict(np.array(img)) Image.fromarray(sr_img1) #prediction 2 sr_img3 = model3.predict(np.array(img)) Image.fromarray(sr_img3) #Final prediction; upscaled image sr_img = model.predict(np.array(img)) Image.fromarray(sr_img) #example 2 !wget https://raw.githubusercontent.com/jbhuang0604/SelfExSR/master/data/Urban100/image_SRF_2/img_001_SRF_2_LR.png !mkdir -p data/input/test_images !mv *.png data/input/test_images img1 = Image.open('data/input/test_images/img_001_SRF_2_LR.png') img1 img1.resize(size=(img1.size[0]*4, img1.size[1]*4), resample=Image.BICUBIC) sr1_img1 = model1.predict(np.array(img1)) Image.fromarray(sr1_img1)
model = RRDN(weights='gans') tagout = '_gan' elif args.model == 2: model = RDN(weights='psnr-large') tagout = '_psnr-large' elif args.model == 3: model = RDN(weights='psnr-small') tagout = '_psnr-small' elif args.model == 4: model = RDN(weights='noise-cancel') tagout = '_denoise' else: print("Couldn't resolve model choice to valid value") # Enlarge the image using ISR print("Enlarging {} using {} now\n".format(args.inputFile, tagout)) # Handle patch size selection patchsize = args.patchSize if patchsize == 0: sr_img = model.predict(lr_img) else: sr_img = model.predict(lr_img, by_patch_of_size=patchsize) # Output to an appropriately tagged file outfile = Image.fromarray(sr_img) outputname = str(file_root + tagout + '.png') outfile.save(outputname, 'png', option='optimize') outfile.close() timestring = time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time)) print("Finished in {}".format(timestring))
#processing frames with ascending order name i.e. frame0, frame1, frame2 etc. #print(files) for filename in files: #sorted_images = sorted(filename, key=natural_sort_key) if filename.endswith(".jpg"): img = Image.open(directory + filename) lr_img = np.array(img) #model = RDN(weights='psnr-small') model = RRDN(weights='gans') sr_img = model.predict(lr_img) sr_img = Image.fromarray(sr_img) sr_img.save('Upscaled/' + filename) print(filename)
help="Output file pattern") parser.add_argument('-overwrite', dest="OVERWRITE", action="store_true", help="Overwrite existing images?") a = parser.parse_args() files = getFilenames(a.INPUT_FILE) makeDirectories(a.OUTPUT_FILE) # model = RDN(weights='noise-cancel') model = RRDN(weights='gans') # model = RDN(weights='psnr-small') # model = RDN(weights='psnr-large') for fn in files: basename = getBasename(fn) filenameOut = a.OUTPUT_FILE % basename if not a.OVERWRITE and os.path.isfile(filenameOut): print(f'Already created {filenameOut}') continue img = Image.open(fn) sr_img = model.predict(np.array(img), by_patch_of_size=50) newImg = Image.fromarray(sr_img) newImg.save(filenameOut) print(f'Saved {filenameOut}') print('Done.')