예제 #1
0
def build_image_set(file_path,
                    channels=1,
                    scale=1,
                    convert_ycbcr=True,
                    resampling_method="bicubic",
                    print_console=True):
    true_image = util.set_image_alignment(
        util.load_image(file_path, print_console=print_console), scale)

    if channels == 1 and true_image.shape[2] == 3 and convert_ycbcr:
        true_image = util.convert_rgb_to_y(true_image)

    input_image = util.resize_image_by_pil(true_image,
                                           1.0 / scale,
                                           resampling_method=resampling_method)
    input_interpolated_image = util.resize_image_by_pil(
        input_image, scale, resampling_method=resampling_method)

    return input_image, input_interpolated_image, true_image
예제 #2
0
    def do_for_file(self, file_path, output_folder="output"):

        filename, extension = os.path.splitext(file_path)
        output_folder += "/"
        org_image = util.load_image(file_path)
        util.save_image(output_folder + file_path, org_image)

        if len(org_image.shape
               ) >= 3 and org_image.shape[2] == 3 and self.channels == 1:
            input_y_image = util.convert_rgb_to_y(org_image,
                                                  jpeg_mode=self.jpeg_mode)
            scaled_image = util.resize_image_by_pil(
                input_y_image,
                self.scale,
                resampling_method=self.resampling_method)
            util.save_image(
                output_folder + filename + "_bicubic_y" + extension,
                scaled_image)
            output_y_image = self.do(input_y_image)
            util.save_image(output_folder + filename + "_result_y" + extension,
                            output_y_image)

            scaled_ycbcr_image = util.convert_rgb_to_ycbcr(
                util.resize_image_by_pil(org_image, self.scale,
                                         self.resampling_method),
                jpeg_mode=self.jpeg_mode)
            image = util.convert_y_and_cbcr_to_rgb(output_y_image,
                                                   scaled_ycbcr_image[:, :,
                                                                      1:3],
                                                   jpeg_mode=self.jpeg_mode)
        else:
            scaled_image = util.resize_image_by_pil(
                org_image,
                self.scale,
                resampling_method=self.resampling_method)
            util.save_image(
                output_folder + filename + "_bicubic_y" + extension,
                scaled_image)
            image = self.do(org_image)

        util.save_image(output_folder + filename + "_result" + extension,
                        image)
예제 #3
0
    def evaluate_bicubic(self, file_path, print_console=False):

        true_image = util.set_image_alignment(util.load_image(file_path, print_console=False), self.scale)

        if true_image.shape[2] == 3 and self.channels == 1:
            input_image = loader.build_input_image(true_image, channels=self.channels, scale=self.scale,
                                                   alignment=self.scale, convert_ycbcr=True)
            true_image = util.convert_rgb_to_y(true_image)
        elif true_image.shape[2] == 1 and self.channels == 1:
            input_image = loader.build_input_image(true_image, channels=self.channels, scale=self.scale,
                                                   alignment=self.scale)
        else:
            return None, None

        input_bicubic_image = util.resize_image_by_pil(input_image, self.scale, resampling_method=self.resampling_method)
        psnr, ssim = util.compute_psnr_and_ssim(true_image, input_bicubic_image, border_size=self.psnr_calc_border_size)

        if print_console:
            print("PSNR:%f, SSIM:%f" % (psnr, ssim))

        return psnr, ssim
예제 #4
0
    def do_for_file(self, file_path, output_folder="output"):
        org_image = util.load_image(file_path)

        filename, extension = os.path.splitext(os.path.basename(file_path))
        output_folder += "/" + self.name + "/"
        util.save_image(output_folder + filename + extension, org_image)

        if len(org_image.shape
               ) >= 3 and org_image.shape[2] == 3 and self.channels == 1:
            input_y_image = util.convert_rgb_to_y(org_image)
            util.save_image(output_folder + filename + '_input_y' + extension,
                            input_y_image)
            scaled_image = util.resize_image_by_pil(
                input_y_image,
                self.scale,
                resampling_method=self.resampling_method)
            util.save_image(
                output_folder + filename + "_bicubic_y" + extension,
                scaled_image)
            output_y_image = self.do(input_y_image)
            util.save_image(output_folder + filename + "_result_y" + extension,
                            output_y_image)

            scaled_ycbcr_image = util.convert_rgb_to_ycbcr(
                util.resize_image_by_pil(org_image, self.scale,
                                         self.resampling_method))
            _, scaled_cbcr = util.convert_ycbcr_to_y_cbcr(scaled_ycbcr_image)
            image = util.convert_y_and_cbcr_to_rgb(output_y_image, scaled_cbcr)
        else:
            scaled_image = util.resize_image_by_pil(
                org_image,
                self.scale,
                resampling_method=self.resampling_method)
            util.save_image(
                output_folder + filename + "_bicubic_y" + extension,
                scaled_image)
            image = self.do(org_image)

        util.save_image(output_folder + filename + "_result" + extension,
                        image)
예제 #5
0
def main(not_parsed_args):
    if len(not_parsed_args) > 1:
        print("Unknown args:%s" % not_parsed_args)
        exit()

    print("Building Y channel data...")

    training_filenames = util.get_files_in_directory(FLAGS.data_dir + "/" +
                                                     FLAGS.dataset + "/")
    target_dir = FLAGS.data_dir + "/" + FLAGS.dataset + "_y/"
    util.make_dir(target_dir)

    for file_path in training_filenames:
        org_image = util.load_image(file_path)
        if org_image.shape[2] == 3:
            org_image = util.convert_rgb_to_y(org_image)

        filename = os.path.basename(file_path)
        filename, extension = os.path.splitext(filename)

        new_filename = target_dir + filename
        util.save_image(new_filename + ".bmp", org_image)
예제 #6
0
    def do_for_file(self, file_path, output_folder="output"):

        org_image = util.load_image(file_path)

        filename, extension = os.path.splitext(os.path.basename(file_path))
        output_folder += "/" + self.name + "/"
        # util.save_image(output_folder + filename + extension, org_image)

        if os.path.exists(output_folder + filename + extension):
            print("File already exists in the target directory")
            return

        if org_image.shape[0] + org_image.shape[1] >= 1024:
            print("Image is too big: ", org_image.shape)
            image = org_image
        elif len(org_image.shape
                 ) >= 3 and org_image.shape[2] == 3 and self.channels == 1:
            input_y_image = util.convert_rgb_to_y(org_image)
            # scaled_image = util.resize_image_by_pil(input_y_image, self.scale, resampling_method=self.resampling_method)
            # util.save_image(output_folder + filename + "_bicubic_y" + extension, scaled_image)
            output_y_image = self.do(input_y_image)
            # util.save_image(output_folder + filename + "_result_y" + extension, output_y_image)

            scaled_ycbcr_image = util.convert_rgb_to_ycbcr(
                util.resize_image_by_pil(org_image, self.scale,
                                         self.resampling_method))
            image = util.convert_y_and_cbcr_to_rgb(
                output_y_image, scaled_ycbcr_image[:, :, 1:3])
        else:
            # scaled_image = util.resize_image_by_pil(org_image, self.scale, resampling_method=self.resampling_method)
            # util.save_image(output_folder + filename + "_bicubic_y" + extension, scaled_image)
            image = self.do(org_image)

        # util.save_image(output_folder + filename + "_result" + extension, image)
        file_path = output_folder + filename + extension
        util.save_image(file_path, image)
        print("Saved at ", file_path)
예제 #7
0
def main(not_parsed_args):
    if len(not_parsed_args) > 1:
        print("Unknown args:%s" % not_parsed_args)
        exit()

    print("Building x%d augmented data." % FLAGS.augment_level)

    training_filenames = util.get_files_in_directory(
        "/media/data3/ww/sr_data/DIV2K_train_HR/")
    target_dir = "/media/data3/ww/sr_data/DIV2K_train_HR" + (
        "_%d/" % FLAGS.augment_level)
    util.make_dir(target_dir)

    writer = tf.python_io.TFRecordWriter("DIV2K_org.tfrecords")
    writer2 = tf.python_io.TFRecordWriter("DIV2K_aug.tfrecords")
    for file_path in training_filenames:
        org_image = util.load_image(file_path)
        org_raw = org_image.tobytes()  #convert image to bytes

        train_object = tf.train.Example(features=tf.train.Features(
            feature={
                'org_raw':
                tf.train.Feature(bytes_list=tf.train.BytesList(
                    value=[org_raw]))
            }))
        writer.write(train_object.SerializeToString())

        ud_image = np.flipud(org_image)
        ud_raw = ud_image.tobytes()  # convert image to bytes

        train_object2 = tf.train.Example(features=tf.train.Features(
            feature={
                'org_raw':
                tf.train.Feature(bytes_list=tf.train.BytesList(value=[ud_raw]))
            }))
        writer2.write(train_object2.SerializeToString())
    writer.close()
예제 #8
0
    def load_random_patch(self, filename):

        image = util.load_image(filename, print_console=False)
        height, width = image.shape[0:2]

        load_batch_size = self.batch_image_size * self.scale

        if height < load_batch_size or width < load_batch_size:
            print("Error: %s should have more than %d x %d size." % (filename, load_batch_size, load_batch_size))
            return None

        if height == load_batch_size:
            y = 0
        else:
            y = random.randrange(height - load_batch_size)

        if width == load_batch_size:
            x = 0
        else:
            x = random.randrange(width - load_batch_size)
        image = image[y:y + load_batch_size, x:x + load_batch_size, :]
        image = build_input_image(image, channels=self.channels, convert_ycbcr=True)

        return image
예제 #9
0
파일: LFFN.py 프로젝트: qibao77/LFFN
    def do_for_evaluate_with_output(self,
                                    file_path,
                                    output_directory,
                                    print_console=False):

        filename, extension = os.path.splitext(file_path)
        output_directory += "/" + self.name + "/"
        util.make_dir(output_directory)

        true_image = util.set_image_alignment(
            util.load_image(file_path, print_console=False), self.scale)

        if true_image.shape[2] == 3 and self.channels == 3:

            # for color images
            input_image = util.build_input_image(true_image,
                                                 scale=self.scale,
                                                 alignment=self.scale)
            input_bicubic_image = util.resize_image_by_pil(
                input_image,
                self.scale,
                resampling_method=self.resampling_method)

            output_image, spend_time = self.do(input_image)  # SR

            SR_y = eva.convert_rgb_to_y(output_image)
            HR_y = eva.convert_rgb_to_y(true_image)
            psnr_predicted = eva.PSNR(np.uint8(HR_y),
                                      np.uint8(SR_y),
                                      shave_border=self.psnr_calc_border_size)
            ssim_predicted = eva.compute_ssim(np.squeeze(HR_y),
                                              np.squeeze(SR_y))

            mse = util.compute_mse(HR_y,
                                   SR_y,
                                   border_size=self.psnr_calc_border_size)
            loss_image = util.get_loss_image(
                HR_y, SR_y, border_size=self.psnr_calc_border_size)

            util.save_image(output_directory + file_path[29:], true_image)
            util.save_image(
                output_directory + filename[28:] + "_input" + extension,
                input_image)
            util.save_image(
                output_directory + filename[28:] + "_input_bicubic" +
                extension, input_bicubic_image)
            util.save_image(
                output_directory + filename[28:] + "_sr" + extension,
                output_image)
            util.save_image(
                output_directory + filename[28:] + "_loss" + extension,
                loss_image)

        elif true_image.shape[2] == 1 and self.channels == 1:
            # for monochrome images
            input_image = util.build_input_image(true_image,
                                                 scale=self.scale,
                                                 alignment=self.scale)
            output_image, spend_time = self.do(input_image)

            psnr_predicted = eva.PSNR(np.uint8(true_image),
                                      np.uint8(output_image),
                                      shave_border=self.psnr_calc_border_size)
            ssim_predicted = eva.compute_ssim(np.squeeze(true_image),
                                              np.squeeze(output_image))

            mse = util.compute_mse(true_image,
                                   output_image,
                                   border_size=self.psnr_calc_border_size)
            util.save_image(output_directory + file_path, true_image)
            util.save_image(output_directory + filename + "_sr" + extension,
                            output_image)
        else:
            psnr_predicted = 0.0
            ssim_predicted = 0.0
            mse = 0.0
            spend_time = 0.0

        if print_console:
            print("[%s] psnr:%f, ssim:%f, time:%f" %
                  (filename, psnr_predicted, ssim_predicted, spend_time))

        return mse, psnr_predicted, ssim_predicted, spend_time
예제 #10
0
    def log_to_tensorboard(self, test_filename, psnr, save_meta_data=True):

        if self.enable_log is False:
            return

        # todo
        save_meta_data = False

        org_image = util.set_image_alignment(
            util.load_image(test_filename, print_console=False), self.scale)

        if len(org_image.shape
               ) >= 3 and org_image.shape[2] == 3 and self.channels == 1:
            org_image = util.convert_rgb_to_y(org_image)

        input_image = util.resize_image_by_pil(
            org_image,
            1.0 / self.scale,
            resampling_method=self.resampling_method)
        bicubic_image = util.resize_image_by_pil(
            input_image, self.scale, resampling_method=self.resampling_method)

        if self.max_value != 255.0:
            input_image = np.multiply(input_image, self.max_value /
                                      255.0)  # type: np.ndarray
            bicubic_image = np.multiply(bicubic_image, self.max_value /
                                        255.0)  # type: np.ndarray
            org_image = np.multiply(org_image,
                                    self.max_value / 255.0)  # type: np.ndarray

        feed_dict = {
            self.x:
            input_image.reshape([
                1, input_image.shape[0], input_image.shape[1],
                input_image.shape[2]
            ]),
            self.x2:
            bicubic_image.reshape([
                1, bicubic_image.shape[0], bicubic_image.shape[1],
                bicubic_image.shape[2]
            ]),
            self.y:
            org_image.reshape([
                1, org_image.shape[0], org_image.shape[1], org_image.shape[2]
            ]),
            self.dropout:
            1.0,
            self.is_training:
            0
        }

        if save_meta_data:
            # profiler = tf.profiler.Profile(self.sess.graph)

            run_metadata = tf.RunMetadata()
            run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
            summary_str, _ = self.sess.run([self.summary_op, self.loss],
                                           feed_dict=feed_dict,
                                           options=run_options,
                                           run_metadata=run_metadata)
            self.test_writer.add_run_metadata(run_metadata,
                                              "step%d" % self.epochs_completed)

            filename = self.checkpoint_dir + "/" + self.name + "_metadata.txt"
            with open(filename, "w") as out:
                out.write(str(run_metadata))

            # filename = self.checkpoint_dir + "/" + self.name + "_memory.txt"
            # tf.profiler.write_op_log(
            # 	tf.get_default_graph(),
            # 	log_dir=self.checkpoint_dir,
            # 	#op_log=op_log,
            # 	run_meta=run_metadata)

            tf.contrib.tfprof.model_analyzer.print_model_analysis(
                tf.get_default_graph(),
                run_meta=run_metadata,
                tfprof_options=tf.contrib.tfprof.model_analyzer.
                PRINT_ALL_TIMING_MEMORY)

        else:
            summary_str, _ = self.sess.run([self.summary_op, self.loss],
                                           feed_dict=feed_dict)

        self.train_writer.add_summary(summary_str, self.epochs_completed)
        if not self.use_l1_loss:
            if self.training_step != 0:
                util.log_scalar_value(
                    self.train_writer, 'PSNR',
                    self.training_psnr_sum / self.training_step,
                    self.epochs_completed)
        util.log_scalar_value(self.train_writer, 'LR', self.lr,
                              self.epochs_completed)
        self.train_writer.flush()

        util.log_scalar_value(self.test_writer, 'PSNR', psnr,
                              self.epochs_completed)
        self.test_writer.flush()
예제 #11
0
def load_input_batch_image(batch_dir, image_number):
	return util.load_image(batch_dir + "/" + INPUT_IMAGE_DIR + "/%06d.bmp" % image_number, print_console=False)
예제 #12
0
    def do_for_evaluate(self,
                        file_path,
                        output_directory=None,
                        print_console=False,
                        save_output_images=True):
        if save_output_images:
            filename, extension = os.path.splitext(file_path)
            output_directory += "/" + self.name + "/"
            util.make_dir(output_directory)

        true_image = util.set_image_alignment(
            util.load_image(file_path, print_console=False), self.scale)

        if true_image.shape[2] == 3 and self.channels == 1:

            # for color images
            input_y_image = loader.build_input_image(true_image,
                                                     channels=self.channels,
                                                     scale=self.scale,
                                                     alignment=self.scale,
                                                     convert_ycbcr=True)
            input_bicubic_y_image = util.resize_image_by_pil(
                input_y_image,
                self.scale,
                resampling_method=self.resampling_method)

            true_ycbcr_image = util.convert_rgb_to_ycbcr(true_image)

            start = time.time()
            output_y_image = self.do(input_y_image, input_bicubic_y_image)
            end = time.time()
            psnr, ssim = util.compute_psnr_and_ssim(
                true_ycbcr_image[:, :, 0:1],
                output_y_image,
                border_size=self.psnr_calc_border_size)
            loss_image = util.get_loss_image(
                true_ycbcr_image[:, :, 0:1],
                output_y_image,
                border_size=self.psnr_calc_border_size)

            output_color_image = util.convert_y_and_cbcr_to_rgb(
                output_y_image, true_ycbcr_image[:, :, 1:3])

            if save_output_images:
                util.save_image(output_directory + file_path, true_image)
                util.save_image(
                    output_directory + filename + "_input" + extension,
                    input_y_image)
                util.save_image(
                    output_directory + filename + "_input_bicubic" + extension,
                    input_bicubic_y_image)
                util.save_image(
                    output_directory + filename + "_true_y" + extension,
                    true_ycbcr_image[:, :, 0:1])
                util.save_image(
                    output_directory + filename + "_result" + extension,
                    output_y_image)
                util.save_image(
                    output_directory + filename + "_result_c" + extension,
                    output_color_image)
                util.save_image(
                    output_directory + filename + "_loss" + extension,
                    loss_image)

        elif true_image.shape[2] == 1 and self.channels == 1:

            # for monochrome images
            input_image = loader.build_input_image(true_image,
                                                   channels=self.channels,
                                                   scale=self.scale,
                                                   alignment=self.scale)
            input_bicubic_y_image = util.resize_image_by_pil(
                input_image,
                self.scale,
                resampling_method=self.resampling_method)
            start = time.time()
            output_image = self.do(input_image, input_bicubic_y_image)
            end = time.time()
            psnr, ssim = util.compute_psnr_and_ssim(
                true_image,
                output_image,
                border_size=self.psnr_calc_border_size)
            if save_output_images:
                util.save_image(output_directory + file_path, true_image)
                util.save_image(
                    output_directory + filename + "_result" + extension,
                    output_image)
        else:
            return None, None
        if print_console:
            print("[%s] PSNR:%f, SSIM:%f" % (filename, psnr, ssim))
        elapsed_time = end - start
        return psnr, ssim, elapsed_time
예제 #13
0
def load_input_image(filename, width=0, height=0, channels=1, scale=1, alignment=0, convert_ycbcr=True,
                     print_console=True):
    image = util.load_image(filename, print_console=print_console)
    return build_input_image(image, width, height, channels, scale, alignment, convert_ycbcr)
예제 #14
0
    def do_for_evaluate_with_output(self,
                                    file_path,
                                    output_directory=None,
                                    print_console=False):
        true_image = util.set_image_alignment(
            util.load_image(file_path, print_console=False), self.scale)

        # Assuming the image is color
        assert true_image.shape[
            2] == 3 and self.channels == 1, "Only 3-channel images are supported"

        input_image = loader.build_input_image(true_image,
                                               scale=self.scale,
                                               alignment=self.scale)

        input_y_image = util.convert_rgb_to_y(input_image)
        true_y_image = util.convert_rgb_to_y(true_image)
        input_bicubic_y_image = util.resize_image_by_pil(
            input_y_image,
            self.scale,
            resampling_method=self.resampling_method)

        output_y_image = self.do(input_y_image, input_bicubic_y_image)

        psnr, ssim = util.compute_psnr_and_ssim(
            true_y_image,
            output_y_image,
            border_size=self.psnr_calc_border_size)

        if output_directory:
            true_ycbcr_image = util.convert_rgb_to_ycbcr(true_image)
            _, true_cbcr = util.convert_ycbcr_to_y_cbcr(true_ycbcr_image)
            output_color_image = util.convert_y_and_cbcr_to_rgb(
                output_y_image, true_cbcr)

            loss_image = util.get_loss_image(
                true_y_image,
                output_y_image,
                border_size=self.psnr_calc_border_size)

            filename, extension = os.path.splitext(file_path)
            output_directory += "/" + self.name + "/"
            util.make_dir(output_directory)

            util.save_image(output_directory + file_path, true_image)
            util.save_image(output_directory + filename + "_input" + extension,
                            input_y_image)
            util.save_image(
                output_directory + filename + "_input_bicubic" + extension,
                input_bicubic_y_image)
            util.save_image(
                output_directory + filename + "_true_y" + extension,
                true_ycbcr_image[:, :, 0:1])
            util.save_image(
                output_directory + filename + "_result" + extension,
                output_y_image)
            util.save_image(
                output_directory + filename + "_result_c" + extension,
                output_color_image)
            util.save_image(output_directory + filename + "_loss" + extension,
                            loss_image)

        if print_console:
            print("[%s] PSNR:%f, SSIM:%f" % (filename, psnr, ssim))

        return psnr, ssim
예제 #15
0
def load_interpolated_batch_image(batch_dir, image_number):
	return util.load_image(batch_dir + "/" + INTERPOLATED_IMAGE_DIR + "/%06d.bmp" % image_number, print_console=False)
예제 #16
0
파일: LFFN.py 프로젝트: qibao77/LFFN
    def log_to_tensorboard(self, test_filename, psnr, save_meta_data=True):

        # todo
        save_meta_data = False

        org_image = util.set_image_alignment(
            util.load_image(test_filename, print_console=False), self.scale)

        if len(org_image.shape
               ) >= 3 and org_image.shape[2] == 3 and self.channels == 1:
            org_image = util.convert_rgb_to_y(org_image)

        input_image = util.resize_image_by_pil(
            org_image,
            1.0 / self.scale,
            resampling_method=self.resampling_method)

        feed_dict = {
            self.x:
            input_image.reshape([
                1, input_image.shape[0], input_image.shape[1],
                input_image.shape[2]
            ]),
            self.y:
            org_image.reshape([
                1, org_image.shape[0], org_image.shape[1], org_image.shape[2]
            ]),
            self.is_training:
            0
        }

        if save_meta_data:
            run_metadata = tf.RunMetadata()
            run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
            summary_str, _ = self.sess.run([self.summary_op, self.mae],
                                           feed_dict=feed_dict,
                                           options=run_options,
                                           run_metadata=run_metadata)
            self.test_writer.add_run_metadata(run_metadata,
                                              "step%d" % self.epochs_completed)

            filename = self.checkpoint_dir + "/" + self.name + "_metadata.txt"
            with open(filename, "w") as out:
                out.write(str(run_metadata))

            tf.contrib.tfprof.model_analyzer.print_model_analysis(
                tf.get_default_graph(),
                run_meta=run_metadata,
                tfprof_options=tf.contrib.tfprof.model_analyzer.
                PRINT_ALL_TIMING_MEMORY)

        else:
            summary_str, _ = self.sess.run([self.summary_op, self.mae],
                                           feed_dict=feed_dict)

        self.train_writer.add_summary(summary_str, self.epochs_completed)
        util.log_scalar_value(self.train_writer, 'training_PSNR',
                              self.training_psnr_sum / self.training_step,
                              self.epochs_completed)
        util.log_scalar_value(self.train_writer, 'LR', self.lr,
                              self.epochs_completed)
        self.train_writer.flush()

        util.log_scalar_value(self.test_writer, 'PSNR', psnr,
                              self.epochs_completed)
        self.test_writer.flush()
예제 #17
0
def load_true_batch_image(batch_dir, image_number):
	return util.load_image(batch_dir + "/" + TRUE_IMAGE_DIR + "/%06d.bmp" % image_number, print_console=False)
예제 #18
0
    def do_for_evaluate(self,
                        file_path,
                        output_directory="output",
                        output=True,
                        print_console=False):

        filename, extension = os.path.splitext(file_path)
        output_directory += "/" + self.name + "/"
        util.make_dir(output_directory)
        true_image = util.set_image_alignment(
            util.load_image(file_path, print_console=False), self.scale)

        if true_image.shape[2] == 3 and self.channels == 1:
            input_y_image = loader.build_input_image(true_image,
                                                     channels=self.channels,
                                                     scale=self.scale,
                                                     alignment=self.scale,
                                                     convert_ycbcr=True,
                                                     jpeg_mode=self.jpeg_mode)
            # for color images
            if output:
                input_bicubic_y_image = util.resize_image_by_pil(
                    input_y_image,
                    self.scale,
                    resampling_method=self.resampling_method)

                true_ycbcr_image = util.convert_rgb_to_ycbcr(
                    true_image, jpeg_mode=self.jpeg_mode)

                output_y_image = self.do(input_y_image, input_bicubic_y_image)
                mse = util.compute_mse(true_ycbcr_image[:, :, 0:1],
                                       output_y_image,
                                       border_size=6 + self.scale)
                loss_image = util.get_loss_image(true_ycbcr_image[:, :, 0:1],
                                                 output_y_image,
                                                 border_size=self.scale)

                output_color_image = util.convert_y_and_cbcr_to_rgb(
                    output_y_image,
                    true_ycbcr_image[:, :, 1:3],
                    jpeg_mode=self.jpeg_mode)

                util.save_image(output_directory + file_path, true_image)
                util.save_image(
                    output_directory + filename + "_input" + extension,
                    input_y_image)
                util.save_image(
                    output_directory + filename + "_input_bicubic" + extension,
                    input_bicubic_y_image)
                util.save_image(
                    output_directory + filename + "_true_y" + extension,
                    true_ycbcr_image[:, :, 0:1])
                util.save_image(
                    output_directory + filename + "_result" + extension,
                    output_y_image)
                util.save_image(
                    output_directory + filename + "_result_c" + extension,
                    output_color_image)
                util.save_image(
                    output_directory + filename + "_loss" + extension,
                    loss_image)
            else:
                true_y_image = util.convert_rgb_to_y(true_image,
                                                     jpeg_mode=self.jpeg_mode)
                input_bicubic_y_image = util.resize_image_by_pil(
                    input_y_image,
                    self.scale,
                    resampling_method=self.resampling_method)
                output_y_image = self.do(input_y_image, input_bicubic_y_image)
                mse = util.compute_mse(true_y_image,
                                       output_y_image,
                                       border_size=6 + self.scale)

        elif true_image.shape[2] == 1 and self.channels == 1:

            # for monochrome images
            input_image = loader.build_input_image(true_image,
                                                   channels=self.channels,
                                                   scale=self.scale,
                                                   alignment=self.scale)
            input_bicubic_y_image = util.resize_image_by_pil(
                input_image,
                self.scale,
                resampling_method=self.resampling_method)
            output_image = self.do(input_image, input_bicubic_y_image)
            mse = util.compute_mse(true_image,
                                   output_image,
                                   border_size=6 + self.scale)
            if output:
                util.save_image(output_directory + file_path, true_image)
                util.save_image(
                    output_directory + filename + "_result" + extension,
                    output_image)
        else:
            mse = 0

        if print_console:
            print("MSE:%f, PSNR:%f" % (mse, util.get_psnr(mse)))

        return mse
예제 #19
0
def load_and_evaluate_tflite_graph(
    output_dir,
    data_dir,
    test_data,
    model_path=os.path.join(os.getcwd(),
                            'model_to_freeze/converted_model.tflite')):
    # https://stackoverflow.com/questions/50443411/how-to-load-a-tflite-model-in-script
    # https://www.tensorflow.org/lite/convert/python_api#tensorflow_lite_python_interpreter_
    output_directory = output_dir
    output_directory += "/" + "tflite" + "/"
    util.make_dir(output_directory)

    test_filepaths = util.get_files_in_directory(data_dir + "/" + test_data)
    total_psnr = total_ssim = total_time = 0

    # Load TFLite model and allocate tensors.
    interpreter = tf.lite.Interpreter(model_path=model_path)
    # interpreter = tf.contrib.lite.Interpreter(model_path=model_path)
    interpreter.allocate_tensors()

    # Get input and output tensors.
    input_details = interpreter.get_input_details()
    output_details = interpreter.get_output_details()

    for file_path in test_filepaths:
        # split filename from extension
        filename, extension = os.path.splitext(file_path)

        # prepare true image
        true_image = util.set_image_alignment(
            util.load_image(file_path, print_console=False), FLAGS.scale)

        # start the timer
        if true_image.shape[2] == 3 and FLAGS.channels == 1:
            # prepare input and ground truth images
            input_y_image = loader.build_input_image(true_image,
                                                     channels=FLAGS.channels,
                                                     scale=FLAGS.scale,
                                                     alignment=FLAGS.scale,
                                                     convert_ycbcr=True)
            input_bicubic_y_image = util.resize_image_by_pil(
                input_y_image,
                FLAGS.scale,
                resampling_method=FLAGS.resampling_method)
            true_ycbcr_image = util.convert_rgb_to_ycbcr(true_image)

            # pass inputs through the model (need to recast and reshape inputs)
            input_y_image_reshaped = input_y_image.astype('float32')
            input_y_image_reshaped = input_y_image_reshaped.reshape(
                1, input_y_image.shape[0], input_y_image.shape[1],
                FLAGS.channels)

            input_bicubic_y_image_reshaped = input_bicubic_y_image.astype(
                'float32')
            input_bicubic_y_image_reshaped = input_bicubic_y_image_reshaped.reshape(
                1, input_bicubic_y_image.shape[0],
                input_bicubic_y_image.shape[1], FLAGS.channels)

            interpreter.set_tensor(input_details[0]['index'],
                                   input_y_image_reshaped)  # pass x
            interpreter.set_tensor(input_details[1]['index'],
                                   input_bicubic_y_image_reshaped)  # pass x2

            start = time.time()
            interpreter.invoke()
            end = time.time()

            output_y_image = interpreter.get_tensor(
                output_details[0]['index'])  # get y
            # resize the output into an image
            output_y_image = output_y_image.reshape(output_y_image.shape[1],
                                                    output_y_image.shape[2],
                                                    FLAGS.channels)

            # calculate psnr and ssim for the output
            psnr, ssim = util.compute_psnr_and_ssim(
                true_ycbcr_image[:, :, 0:1],
                output_y_image,
                border_size=FLAGS.psnr_calc_border_size)

            # get the loss image
            loss_image = util.get_loss_image(
                true_ycbcr_image[:, :, 0:1],
                output_y_image,
                border_size=FLAGS.psnr_calc_border_size)

            # get output color image
            output_color_image = util.convert_y_and_cbcr_to_rgb(
                output_y_image, true_ycbcr_image[:, :, 1:3])

            # save all images
            util.save_image(output_directory + file_path, true_image)
            util.save_image(output_directory + filename + "_input" + extension,
                            input_y_image)
            util.save_image(
                output_directory + filename + "_input_bicubic" + extension,
                input_bicubic_y_image)
            util.save_image(
                output_directory + filename + "_true_y" + extension,
                true_ycbcr_image[:, :, 0:1])
            util.save_image(
                output_directory + filename + "_result" + extension,
                output_y_image)
            util.save_image(
                output_directory + filename + "_result_c" + extension,
                output_color_image)
            util.save_image(output_directory + filename + "_loss" + extension,
                            loss_image)
        elapsed_time = end - start
        total_psnr += psnr
        total_ssim += ssim
        total_time += elapsed_time
    testSize = len(test_filepaths)
    print("Model Average [%s] PSNR:%f, SSIM:%f, Elapsed Time:%f" %
          (test_data, total_psnr / testSize, total_ssim / testSize,
           total_time / testSize))