Пример #1
0
def callback(ch, method, properties, body):
    work_data = jsonpickle.decode(body)
    id = work_data['id']
    split_filename = work_data['split_filename']
    log(channel, 'info',
        'Received work request for chunk: {}'.format(split_filename))
    start_time = time.time()

    # Get status from DB
    data = db_data.find_one({'id': id})
    if data == None:
        # If id is not in database, ACK here because we don't want an endless worker loop
        ch.basic_ack(delivery_tag=method.delivery_tag)
        raise Exception('No data in database for ID {}'.format(id))

    # Create working directories
    work_path = 'upscale/{}'.format(id)
    os.makedirs(work_path, exist_ok=True)

    # Download chunk
    log(channel, 'debug', 'Downloading chunk: {}'.format(split_filename))
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(split_filename)
    work_file = '{}/{}'.format(work_path, split_filename)
    blob.download_to_filename(work_file)

    # Upscale the chunk
    output_file = '{}_upscaled.avi'.format(split_filename.split('.')[0])
    output_file_path = '{}/{}'.format(work_path, output_file)
    scale_factor = 4
    model = dnn_superres.DnnSuperResImpl_create()
    model.readModel("ESPCN_x4.pb")
    model.setModel("espcn", scale_factor)
    log(channel, 'debug', 'Upscaling chunk: {}'.format(output_file))
    single_process(work_file, output_file_path, model, scale_factor)

    # Upload upscaled chunk
    log(channel, 'debug', 'Uploading chunk: {}'.format(output_file))
    blob = bucket.blob(output_file)
    blob.upload_from_filename(output_file_path)

    # Clean up working directories
    shutil.rmtree(work_path)

    # Update DB status
    completion_time = time.time()
    db_data.update_one({
        'id': id,
        'splits.name': split_filename
    }, {
        '$set': {
            'splits.$.upscale_name': output_file,
            'splits.$.time_start': start_time,
            'splits.$.time_end': completion_time,
            'splits.$.status': 'COMPLETE'
        }
    })

    ch.basic_ack(delivery_tag=method.delivery_tag)
Пример #2
0
def sr_operate(img_path):

    # Create an SR object
    sr = dnn_superres.DnnSuperResImpl_create()

    # Read image
    img_array = np.fromfile(img_path, np.uint8)

    #image = cv2.imread(img_path)
    image = cv2.imdecode(img_array, cv2.IMREAD_COLOR)

    # Read the desired model
    path = "FSRCNN_x4.pb"
    path = os.path.abspath(path)
    sr.readModel(path)

    # Set CUDA backend and target to enable GPU inference
    #sr.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
    #sr.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)

    # Set the desired model and scale to get correct pre- and post-processing
    sr.setModel("fsrcnn", 4)

    # Upscale the image
    result = sr.upsample(image)

    # Save the image
    save_path = "d:\\carz_operated\\sr_img"
    if not os.path.exists(save_path):
        os.mkdir(save_path)
    cv2.imwrite(save_path + "\\upscaled.png", result)
    return save_path + "\\upscaled.png"
Пример #3
0
 def __init__(
     self: Detector,
     config: Config
 ) -> None:
     self.config = config
     # self.model = Model(config=config)
     self.model = None
     dataset_name = config.image_dir.split(os.sep)[-1]
     if self.config.framework == 'tflite':
         self.result_dir = 'results/%s/%s_%s_%s' % (
             dataset_name, config.model,
             config.framework, config.quantize
         )
     else:
         self.result_dir = 'results/%s/%s_%s' % (
             dataset_name, config.model, config.framework
         )
     os.makedirs(self.result_dir, exist_ok=True)
     self.sr = None
     if config.use_superres:
         self.sr = dnn_superres.DnnSuperResImpl_create()
         self.sr.readModel('superres/ESPCN_x4.pb')
         self.sr.setModel('espcn', 4)
     self.wf = open(os.path.join(
         self.result_dir, 'predictions.jsonl'
     ), 'wt')
     return
Пример #4
0
 def _load_superresolution_models():
     data_dir = os.path.dirname(__file__) + '/superresolution/'
     for scale in (2, 4, 8):
         Rescale._sr_dict[scale] = dnn_superres.DnnSuperResImpl_create()
         Rescale._sr_dict[scale].readModel(data_dir + 'LapSRN_x' +
                                           str(scale) + '.pb')
         Rescale._sr_dict[scale].setModel('lapsrn', scale)
Пример #5
0
    def superscale(self, img: Image.Image) -> Image.Image:
        """Performs upsampling using superresolution neural networks.
        At the moment, OpenCV offers four models, three of which you can choose here:
        LAPSRN, ESPCN, FSRCNN. All of which can upsample by the factor of 4.
        Other versions can be downloaded too, the EDSR model is too large and too slow.

        Quellen:
        https://towardsdatascience.com/deep-learning-based-super-resolution-with-opencv-4fd736678066
        https://docs.opencv.org/master/d5/d29/tutorial_dnn_superres_upscale_image_single.html


        Args:
            img (Image.Image): Image to be upscaled.

        Returns:
            Image.Image: The upsampled image.
        """
        superscaler = dnn_superres.DnnSuperResImpl_create()
        model_path = os.path.join(
            'data', 'models',
            f'{self.model_name.upper()}_x{self.scale_factor}.pb')
        superscaler.readModel(model_path)
        superscaler.setModel(self.model_name, self.scale_factor)

        img = img.convert('RGB')
        img = np.array(img)
        img = superscaler.upsample(img)
        img = Image.fromarray(img.astype('uint8'), 'RGB')

        return img
Пример #6
0
    def __init__(self, parent=None):
        super().__init__()
        self.play = True

        self.sr = dnn_superres.DnnSuperResImpl_create()
        self.path = "models/ESPCN_x4.pb"
        self.sr.readModel(self.path)
        self.sr.setModel("espcn", 4)
Пример #7
0
def upScaleEDSR(image):
    # Create an SR object
    sr = dnn_superres.DnnSuperResImpl_create()
    path = "saved_models/EDSR_x3.pb"
    sr.readModel(path)
    # Set the desired model and scale to get correct pre- and post-processing
    sr.setModel("edsr", 3)
    result = sr.upsample(image)
    return result
def main():
    img_path = "./image/image.png"
    # 可选择算法,bilinear, bicubic, edsr, espcn, fsrcnn or lapsrn
    algorithm = "bilinear"
    # 放大比例,可输入值2,3,4
    scale = 4
    # 模型路径
    path = "./model/LapSRN_x4.pb"

    # 载入图像
    img = cv2.imread(img_path)
    # 如果输入的图像为空
    if img is None:
        print("Couldn't load image: " + str(img_path))
        return

    original_img = img.copy()

    # 创建模型
    sr = dnn_superres.DnnSuperResImpl_create()

    if algorithm == "bilinear":
        img_new = cv2.resize(img,
                             None,
                             fx=scale,
                             fy=scale,
                             interpolation=cv2.INTER_LINEAR)
    elif algorithm == "bicubic":
        img_new = cv2.resize(img,
                             None,
                             fx=scale,
                             fy=scale,
                             interpolation=cv2.INTER_CUBIC)
    elif algorithm == "edsr" or algorithm == "espcn" or algorithm == "fsrcnn" or algorithm == "lapsrn":
        # 读取模型
        sr.readModel(path)
        #  设定算法和放大比例
        sr.setModel(algorithm, scale)
        # 放大图像
        img_new = sr.upsample(img)
    else:
        print("Algorithm not recognized")

    # 如果失败
    if img_new is None:
        print("Upsampling failed")

    print("Upsampling succeeded. \n")

    # Display
    # 展示图片
    cv2.namedWindow("Initial Image", cv2.WINDOW_AUTOSIZE)
    # 初始化图片
    cv2.imshow("Initial Image", img_new)
    cv2.imwrite("./saved.jpg", img_new)
    cv2.waitKey(0)
def main():
    input_path = "./video/chaplin.mp4"
    output_path = "./video/out_chaplin.mp4"
    # 选择模型 edsr, espcn, fsrcnn or lapsrn
    algorithm = "lapsrn"
    # 放大比例,2,3,4,8,根据模型结构选择
    scale = 2
    # 模型路径
    path = "./model/LapSRN_x2.pb"

    # 打开视频
    input_video = cv2.VideoCapture(input_path)
    # 输入图像编码尺寸

    ex = int(input_video.get(cv2.CAP_PROP_FOURCC))

    # 获得输出视频图像尺寸
    # 如果视频没有打开
    if input_video is None:
        print("Could not open the video.")
        return

    S = (int(input_video.get(cv2.CAP_PROP_FRAME_WIDTH)) * scale,
         int(input_video.get(cv2.CAP_PROP_FRAME_HEIGHT)) * scale)

    output_video = cv2.VideoWriter(output_path, ex,
                                   input_video.get(cv2.CAP_PROP_FPS), S, True)

    # 读取超分放大模型
    sr = dnn_superres.DnnSuperResImpl_create()
    sr.readModel(path)
    sr.setModel(algorithm, scale)

    while True:
        ret, frame = input_video.read()  # 捕获一帧图像

        if not ret:
            print("read video error")
            return
        # 上采样图像
        output_frame = sr.upsample(frame)
        output_video.write(output_frame)

        cv2.namedWindow("Upsampled video", cv2.WINDOW_AUTOSIZE)
        cv2.imshow("Upsampled video", output_frame)

        cv2.namedWindow("Original video", cv2.WINDOW_AUTOSIZE)
        cv2.imshow("Original video", frame)

        c = cv2.waitKey(1)
        # esc退出
        if 27 == c:
            break

    input_video.release()
    output_video.release()
Пример #10
0
def superresolution(img):
  # Create an SR object
  sr = dnn_superres.DnnSuperResImpl_create()
  # Read the desired model
  path = "/content/drive/My Drive/Images/EDSR_x4.pb"
  sr.readModel(path)
  # Set the desired model and scale to get correct pre- and post-processing
  sr.setModel("edsr", 3)
  # Upscale the image
  img = sr.upsample(img)
  return img
Пример #11
0
    def upscaler(self):
        try:
            self.vid = cv2.VideoCapture(self.filename)
            self.text_image_seq.configure(text='Upscaling Video', anchor='w')

            self.seq_progress.place(relx=0.099, rely=0.505, relwidth=0.791
                                    , relheight=0.0, height=22)
            self.seq_progress.configure(length="400")

            self.pvalue = 100 / self.T_frames
            self.text_image_seq_2.configure(text='''''')
            root.update_idletasks()


            imgs = []
            sr = dnn_superres.DnnSuperResImpl_create()
            path = "datamodel\\ESPCN_x2.pb"
            sr.readModel(path)
            sr.setModel("espcn", 2)
            for i in range(1, self.T_frames + 1):
                ret, frame = self.vid.read()
                upimg = sr.upsample(frame)
                height, width, layers = upimg.shape
                size = (width, height)
                imgs.append(upimg)
                self.seq_progress['value'] += self.pvalue
                root.update_idletasks()
                root.update()

            self.text_image_seq_2.configure(text='''----Upscalling Done----''')
            self.seq_progress['value'] = 0
            print("Exporting Video....")
            self.text_image_seq.configure(text='Exporting Video....', anchor='w')
            root.update_idletasks()

            output = cv2.VideoWriter(str(self.o_direct) + '\\output.avi', cv2.VideoWriter_fourcc(*'DIVX'), 24, size)

            for i in range(self.T_frames):
                # print(i)
                output.write(imgs[i])
                self.seq_progress['value'] += self.pvalue
                root.update_idletasks()
                root.update()

            self.text_image_seq_2.configure(text='''----Video Exported----''')
            print("Video Exported.")


        except:
            self.text_image_seq_2.configure(text='''----Provide a valid Video File----''')
            self.text_image_seq.configure(text='', anchor='w')
            root.update_idletasks()
Пример #12
0
def supper_res(path):
	sr = dnn_superres.DnnSuperResImpl_create()
	image = cv2.imread(path)
	modelPath = "ESPCN_x4.pb"
	sr.readModel(modelPath)
	sr.setModel("espcn", 4)
	imls=np.array_split(image,4)
	for i in range(len(imls)):
		imls[i]=sr.upsample(imls[i])
		print(i)
	result=np.concatenate(imls)
	#result = cv2.merge((sr.upsample(b),sr.upsample(g),sr.upsample(r)))
	cv2.imwrite(path[:-4]+"_Large.jpg", result)
	return path[:-4]+"_Large.jpg"
Пример #13
0
def super_resolution(image: np.ndarray) -> np.ndarray:
    # Create an SR object
    sr = dnn_superres.DnnSuperResImpl_create()

    # Read the desired model
    path = "/home/appuser/data/weight_for_super_resolution/EDSR_x4.pb"
    sr.readModel(path)

    # Set the desired model and scale to get correct pre- and post-processing
    sr.setModel("edsr", 4)

    # Upscale the image
    upsampled = sr.upsample(image)

    return upsampled
Пример #14
0
def upscale(image):
    sr = dnn_superres.DnnSuperResImpl_create()

    edsr_model_path = Path("/watercolor-processing/models/EDSR_x3.pb")
    fsr_model_path = Path("/watercolor-processing/models/FSRCNN_x3.pb")

    #print("model path: ", model_path, flush=True)
    sr.readModel(str(fsr_model_path))

    #"edsr" or "fsrcnn"
    sr.setModel("fsrcnn", 3)
    print(f"started upscaling image with shape: {image.shape}")
    result = sr.upsample(image)
    print(f"finished upscaling image: {result.shape}")
    return result
Пример #15
0
def upscale(path, guildId):
    start_time = time.time()
    sr = dnn_superres.DnnSuperResImpl_create()
    image_path = cv2.imread(path)

    # change path to change model
    model_path = os.path.join(os.getcwd(), "models/EDSR_x3.pb")
    sr.readModel(model_path)

    # first param is the name of the model
    # second param is the scale of the model, scale of the model is in the name of the file of the model
    sr.setModel("edsr", 3)

    result = sr.upsample(image_path)
    cv2.imwrite(path, result)
    print("--- %s seconds ---" % (time.time() - start_time))
Пример #16
0
    def enhance_resolution(self, output_path):
        ''' Enhance the resolution of the image
        using Super Resolution technique '''
        MODEL_PATH = "./assets/FSRCNN_x4.pb"

        img = cv2.imread(self.__file)

        # Apply DNN Super Resolution technique using pre trained model (in our case FSRCNN model)
        sr = dnn_superres.DnnSuperResImpl_create()
        sr.readModel(MODEL_PATH)
        sr.setModel("fsrcnn", 4)

        final_img = sr.upsample(img)

        final_img = cv2.fastNlMeansDenoisingColored(final_img, None, 10, 10, 7,
                                                    15)  # Remove Noise
        self.reduce_img_size(final_img, output_path, "enhanced_resolution")
Пример #17
0
    def test_super_resolution(self):

        # Create an SR object
        sr = dnn_superres.DnnSuperResImpl_create()

        # Read image
        image = cv2.imread(_input_path)

        # Read the desired model
        path = "/home/appuser/data/weight_for_super_resolution/EDSR_x4.pb"
        sr.readModel(path)

        # Set the desired model and scale to get correct pre- and post-processing
        sr.setModel("edsr", 4)

        # Upscale the image
        result = sr.upsample(image)

        # Save the image
        cv2.imwrite(_output_path, result)
Пример #18
0
def scaleUp(source: str, dest: str):
    global scaleFactor, filename, dirname

    # Create an SR object
    sr = dnn_superres.DnnSuperResImpl_create()

    # Read image
    image = cv2.imread(source)

    # Read the desired model
    path = f'{dirname}/Model/LapSRN_x8.pb'
    sr.readModel(path)

    # Set the desired model and scale to get correct pre- and post-processing
    sr.setModel("lapsrn", scaleFactor)

    # Upscale the image
    result = sr.upsample(image)

    # Save the image
    cv2.imwrite(dest, result)
Пример #19
0
def sr_work():
    try:
        # Create an SR object
        sr = dnn_superres.DnnSuperResImpl_create()

        # Read image
        image = cv2.imread('../../image/input.png')

        # Read the desired model
        path = "EDSR_x3.pb"
        sr.readModel(path)

        # Set the desired model and scale to get correct pre- and post-processing
        sr.setModel("edsr", 3)

        # Upscale the image
        result = sr.upsample(image)

        # Save the image
        cv2.imwrite("../../image/upscaled.png", result)
    except:
        print("error")
    def _DNN_SR_processor(self):
        # Create an SR object
        sr = dnn_superres.DnnSuperResImpl_create()

        # Read image
        self.imageLoader.image_directory = self.image
        self.imageLoader.load_image()
        image = self.imageLoader.image_array

        # Read the desired model
        sr.readModel(
            '{cur_dir}/../../../resource/DeepLearningModels/{method_folder}/{method_name}_x{scale_factor}.pb'
            .format(method_folder=self._method,
                    method_name=self._method,
                    scale_factor=self._scale_factor,
                    cur_dir=self.current_dir))

        # Set the desired model and scale to get correct pre- and post-processing
        sr.setModel(self._method.lower(), self._scale_factor)

        # Upscale the image
        result = sr.upsample(image)

        return result
Пример #21
0
def resolute():
    generator = torch.load("WEIGHTS/w2.pth", map_location="cpu")
    generator.eval()
    device = torch.device('cpu')
    generator.to(device)
    y = generator(torch.randn(batch_size, latent_size, 1, 1))
    gen_imgs = denorm(y.detach())
    to_pil_image = transforms.ToPILImage()
    result1 = to_pil_image(gen_imgs[0])
    result2 = to_pil_image(gen_imgs[1])
    result3 = to_pil_image(gen_imgs[2])
    newsize = (70, 70)
    im1 = result1.resize(newsize)
    im2 = result2.resize(newsize)
    im3 = result3.resize(newsize)
    im1 = im1.save("SUPERSAMPLES/new.jpg", quality=100)
    im2 = im2.save("SUPERSAMPLES/new1.jpg", quality=100)
    im3 = im3.save("SUPERSAMPLES/new2.jpg", quality=100)

    sr = dnn_superres.DnnSuperResImpl_create()

    image = cv2.imread('./SUPERSAMPLES/new.jpg')
    image2 = cv2.imread('./SUPERSAMPLES/new1.jpg')
    image3 = cv2.imread('./SUPERSAMPLES/new2.jpg')

    path = "LapSRN_x8.pb"
    sr.readModel(path)

    sr.setModel("lapsrn", 8)

    result = sr.upsample(image)
    result1 = sr.upsample(image2)
    result2 = sr.upsample(image3)

    cv2.imwrite("./SUPERSAMPLES/supernew.png", result)
    cv2.imwrite("./SUPERSAMPLES/supernew1.png", result1)
Пример #22
0
def upscale(image_path,
            model_name,
            model_path,
            scale,
            output_path='./upscaled.png'):
    if model_name not in models:
        print('{0} not a valid model'.format(model_name))
        return
    sr = dnn_superres.DnnSuperResImpl_create()

    image = cv2.imread(image_path)
    sr.readModel(model_path)

    # code for CUDA acceleration
    # to use, opencv must be built with cuda support
    # sr.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
    # sr.setPreferableBackend(cv2.dnn.DNN_TARGET_CUDA)

    # set the desired model and scale
    sr.setModel(model_name, scale)

    upscaled_image = sr.upsample(image)

    cv2.imwrite(output_path, upscaled_image)
Пример #23
0
import cv2
from cv2 import dnn_superres
# Create an SR object - only function that differs from c++ code
sr = dnn_superres.DnnSuperResImpl_create()
# Read image
image = cv2.imread('./file_250.jpg')
# Read the desired model
path = "ESPCN_x3.pb"
sr.readModel(path)
# Set the desired model and scale to get correct pre- and post-processing
sr.setModel("espcn", 3)
# Upscale the image
result = sr.upsample(image)
# Save the image
cv2.imwrite("./upscaled.jpg", result)
Пример #24
0
def get_superscaler():
    super_res = dnn_superres.DnnSuperResImpl_create()
    path = get_model_path()
    super_res.readModel(path)
    super_res.setModel(superres_settings["model"], superres_settings["scale"])
    return super_res
Пример #25
0
    def timeslide(self):

        # colorization
        if (self.colorize_int.get() == 1):

            # set status
            self.label_status.config(text="Colorizing. Please stand by...")
            self.update()

            # determine colorizer model
            if (self.model_vars.get() == "Artistic"):
                colorizer = get_image_colorizer(artistic=True)
            elif (self.model_vars.get() == "Stable"):
                colorizer = get_image_colorizer(artistic=False)

            # get render factor
            render_factor = self.scale_rf.get()

            if self.load_method in "open_file":
                self.result_path = colorizer.plot_transformed_image(
                    path=self.file_path,
                    render_factor=render_factor,
                    compare=False)
            elif self.load_method in "load_url":
                print(self.str_url.get("1.0", tk.END))
                self.result_path = colorizer.plot_transformed_image_from_url(
                    url=self.str_url.get("1.0", tk.END),
                    path='//tmp/tmp.png',
                    render_factor=render_factor,
                    compare=False)
            self.img_base = Image.open(self.result_path)

            # display to canvas
            self.show_image()

        # do enhancement
        if (self.enhance_int.get() == 1):

            # set status
            self.label_status.config(text="Enhancing. Please stand by...")
            self.update()

            # determine which file we're reading
            if (self.colorize_int.get() == 1):
                filepath = self.result_path
            else:
                filepath = self.file_path

            # Create an SR object
            sr = dnn_superres.DnnSuperResImpl_create()

            # Read image
            image = cv2.imread(str(filepath))

            # Read the desired model, enhance factor
            model = self.weights_vars.get()
            enhance_factor = int(self.scale_ef.get())
            path = "models/%s_x%i.pb" % (model, enhance_factor)
            sr.readModel(path)

            # Set the desired model and scale to get correct pre- and post-processing
            sr.setModel(model.lower(), enhance_factor)

            # Upscale the image
            result = sr.upsample(image)

            # Save the image
            self.result_path = './tmp_enhance.jpg'
            cv2.imwrite(self.result_path, result)

            # display to canvas
            self.img_base = Image.open(self.result_path)
            self.show_image()

        # set status to complete
        self.label_status.config(text="TimeSlide complete!")

        # enable save button
        self.btn_save_photo['state'] = 'normal'
def main():
    # 图片路径
    img_path = "./image/image.png"
    # 算法名称 edsr, espcn, fsrcnn or lapsrn
    algorithm = "lapsrn"
    # 模型路径,根据算法确定
    model = "./model/LapSRN_x2.pb"
    # 放大系数
    scale = 2
    # 时间系数
    perf = []

    img = cv2.imread(img_path)

    if img is None:
        print("Couldn't load image: " + str(img_path))

    # Crop the image so the images will be aligned
    # 裁剪图像,使图像对齐
    width = img.shape[0] - (img.shape[0] % scale)
    height = img.shape[1] - (img.shape[1] % scale)
    cropped = img[0:width, 0:height]

    # Downscale the image for benchmarking
    # 缩小图像,以实现基准质量测试
    img_downscaled = cv2.resize(cropped, None, fx=1.0 / scale, fy=1.0 / scale)

    # Make dnn super resolution instance
    # 超分模型初始化
    sr = dnn_superres.DnnSuperResImpl_create()

    # Read and set the dnn model
    # 读取和设定模型
    sr.readModel(model)
    sr.setModel(algorithm, scale)

    timer = cv2.TickMeter()
    timer.start()
    # 放大图像
    img_new = sr.upsample(img_downscaled)
    timer.stop()
    # 运行时间s
    elapsed = timer.getTimeSec() / timer.getCounter()
    perf.append(elapsed)
    print(sr.getAlgorithm() + " : " + str(elapsed))

    # INTER_CUBIC - 三次样条插值放大图像
    timer.start()
    bicubic = cv2.resize(img_downscaled,
                         None,
                         fx=scale,
                         fy=scale,
                         interpolation=cv2.INTER_CUBIC)
    timer.stop()
    # 运行时间s
    elapsed = timer.getTimeSec() / timer.getCounter()
    perf.append(elapsed)
    print("Bicubic" + " : " + str(elapsed))

    # INTER_NEAREST - 最近邻插值
    timer.start()
    nearest = cv2.resize(img_downscaled,
                         None,
                         fx=scale,
                         fy=scale,
                         interpolation=cv2.INTER_NEAREST)
    timer.stop()
    # 运行时间s
    elapsed = timer.getTimeSec() / timer.getCounter()
    perf.append(elapsed)
    print("Nearest" + " : " + str(elapsed))

    # Lanczos插值放大图像
    timer.start()
    lanczos = cv2.resize(img_downscaled,
                         None,
                         fx=scale,
                         fy=scale,
                         interpolation=cv2.INTER_LANCZOS4)
    timer.stop()
    # 运行时间s
    elapsed = timer.getTimeSec() / timer.getCounter()
    perf.append(elapsed)
    print("Lanczos" + " : " + str(elapsed))

    imgs = [img_new, bicubic, nearest, lanczos]
    titles = [sr.getAlgorithm(), "Bicubic", "Nearest neighbor", "Lanczos"]
    showBenchmark(imgs, titles, perf)
Пример #27
0
def main():
    # 图片路径
    img_path = "./image/butterfly.png"
    # 算法名称 edsr, espcn, fsrcnn or lapsrn
    algorithm = "lapsrn"
    # 模型路径,根据算法确定
    model = "./model/LapSRN_x2.pb"
    # 放大系数
    scale = 2
    psnrValues = []
    ssimValues = []

    img = cv2.imread(img_path)

    if img is None:
        print("Couldn't load image: " + str(img_path))

    # Crop the image so the images will be aligned
    # 裁剪图像,使图像对齐
    width = img.shape[0] - (img.shape[0] % scale)
    height = img.shape[1] - (img.shape[1] % scale)
    cropped = img[0:width, 0:height]

    # Downscale the image for benchmarking
    # 缩小图像,以实现基准质量测试
    img_downscaled = cv2.resize(cropped, None, fx=1.0 / scale, fy=1.0 / scale)

    # Make dnn super resolution instance
    # 超分模型初始化
    sr = dnn_superres.DnnSuperResImpl_create()

    # Read and set the dnn model
    # 读取和设定模型
    sr.readModel(model)
    sr.setModel(algorithm, scale)
    # 放大图像
    img_new = sr.upsample(img_downscaled)

    # DL MODEL
    # 获得模型质量评估值
    psnr, ssim = getQualityValues(cropped, img_new)

    psnrValues.append(psnr)
    ssimValues.append(ssim)

    print(sr.getAlgorithm() + "\n")
    print("PSNR: " + str(psnr) + " SSIM: " + str(ssim) + "\n")
    print("-" * 50)

    # INTER_CUBIC - 三次样条插值放大图像
    bicubic = cv2.resize(img_downscaled, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)
    psnr, ssim = getQualityValues(cropped, bicubic)

    psnrValues.append(psnr)
    ssimValues.append(ssim)

    print("Bicubic \n")
    print("PSNR: " + str(psnr) + " SSIM: " + str(ssim) + "\n")
    print("-" * 50)

    # INTER_NEAREST - 最近邻插值

    nearest = cv2.resize(img_downscaled, None, fx=scale, fy=scale, interpolation=cv2.INTER_NEAREST)
    psnr, ssim = getQualityValues(cropped, nearest)
    psnrValues.append(psnr)
    ssimValues.append(ssim)

    print("Nearest neighbor \n")
    print("PSNR: " + str(psnr) + " SSIM: " + str(ssim) + "\n")
    print("-" * 50)

    # Lanczos插值放大图像

    lanczos = cv2.resize(img_downscaled, None, fx=scale, fy=scale, interpolation=cv2.INTER_LANCZOS4);
    psnr, ssim = getQualityValues(cropped, lanczos)
    psnrValues.append(psnr)
    ssimValues.append(ssim)

    print("Lanczos \n")
    print("PSNR: " + str(psnr) + " SSIM: " + str(ssim) + "\n")
    print("-" * 50)

    imgs = [img_new, bicubic, nearest, lanczos]
    titles = [sr.getAlgorithm(), "Bicubic", "Nearest neighbor", "Lanczos"]
    showBenchmark(imgs, titles, psnrValues, ssimValues)