#!/usr/bin/python # # Copyright (c) 2016, Alliance for Open Media. All rights reserved. # # This source code is subject to the terms of the BSD 2 Clause License and # the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License # was not distributed with this source code in the LICENSE file, you can # obtain it at www.aomedia.org/license/software. If the Alliance for Open # Media Patent License 1.0 was not distributed with this source code in the # PATENTS file, you can obtain it at www.aomedia.org/license/patent. #
"""Converts video encoding result data from text files to visualization
data source."""
def bdsnr2(metric_set1, metric_set2): """
BJONTEGAARD Bjontegaard metric calculation adapted
Bjontegaard's snr metric allows to compute the average % saving in decibels
between two rate-distortion curves [1]. This is an adaptation of that
method that fixes inconsistencies when the curve fit operation goes awry
by replacing the curve fit function with a Piecewise Cubic Hermite
Interpolating Polynomial and then integrating that by evaluating that
function at small intervals using the trapezoid method to calculate
the integral.
metric_set1 - list of tuples ( bitrate, metric ) for first graph
metric_set2 - list of tuples ( bitrate, metric ) for second graph """
ifnot metric_set1 ornot metric_set2: return 0.0
try:
# pchip_interlopate requires keys sorted by x axis. x-axis will # be our metric not the bitrate so sort by metric.
metric_set1.sort()
metric_set2.sort()
# Pull the log of the rate and clamped psnr from metric_sets.
log_rate1 = [math.log(x[0]) for x in metric_set1]
metric1 = [100.0 if x[1] == float('inf') else x[1] for x in metric_set1]
log_rate2 = [math.log(x[0]) for x in metric_set2]
metric2 = [100.0 if x[1] == float('inf') else x[1] for x in metric_set2]
# Integration interval. This metric only works on the area that's # overlapping. Extrapolation of these things is sketchy so we avoid.
min_int = max([min(log_rate1), min(log_rate2)])
max_int = min([max(log_rate1), max(log_rate2)])
# No overlap means no sensible metric possible. if max_int <= min_int: return 0.0
# Use Piecewise Cubic Hermite Interpolating Polynomial interpolation to # create 100 new samples points separated by interval.
lin = np.linspace(min_int, max_int, num=100, retstep=True)
interval = lin[1]
samples = lin[0]
v1 = scipy.interpolate.pchip_interpolate(log_rate1, metric1, samples)
v2 = scipy.interpolate.pchip_interpolate(log_rate2, metric2, samples)
# Calculate the integral using the trapezoid method on the samples.
int_v1 = np.trapz(v1, dx=interval)
int_v2 = np.trapz(v2, dx=interval)
# Calculate the average improvement.
avg_exp_diff = (int_v2 - int_v1) / (max_int - min_int)
except (TypeError, ZeroDivisionError, ValueError, np.RankWarning) as e: return 0
return avg_exp_diff
def bdrate2(metric_set1, metric_set2): """
BJONTEGAARD Bjontegaard metric calculation adapted
Bjontegaard's metric allows to compute the average % saving in bitrate
between two rate-distortion curves [1]. This is an adaptation of that
method that fixes inconsistencies when the curve fit operation goes awry
by replacing the curve fit function with a Piecewise Cubic Hermite
Interpolating Polynomial and then integrating that by evaluating that
function at small intervals using the trapezoid method to calculate
the integral.
metric_set1 - list of tuples ( bitrate, metric ) for first graph
metric_set2 - list of tuples ( bitrate, metric ) for second graph """
ifnot metric_set1 ornot metric_set2: return 0.0
try:
# pchip_interlopate requires keys sorted by x axis. x-axis will # be our metric not the bitrate so sort by metric.
metric_set1.sort(key=lambda tup: tup[1])
metric_set2.sort(key=lambda tup: tup[1])
# Pull the log of the rate and clamped psnr from metric_sets.
log_rate1 = [math.log(x[0]) for x in metric_set1]
metric1 = [100.0 if x[1] == float('inf') else x[1] for x in metric_set1]
log_rate2 = [math.log(x[0]) for x in metric_set2]
metric2 = [100.0 if x[1] == float('inf') else x[1] for x in metric_set2]
# Integration interval. This metric only works on the area that's # overlapping. Extrapolation of these things is sketchy so we avoid.
min_int = max([min(metric1), min(metric2)])
max_int = min([max(metric1), max(metric2)])
# No overlap means no sensible metric possible. if max_int <= min_int: return 0.0
# Use Piecewise Cubic Hermite Interpolating Polynomial interpolation to # create 100 new samples points separated by interval.
lin = np.linspace(min_int, max_int, num=100, retstep=True)
interval = lin[1]
samples = lin[0]
v1 = scipy.interpolate.pchip_interpolate(metric1, log_rate1, samples)
v2 = scipy.interpolate.pchip_interpolate(metric2, log_rate2, samples)
# Calculate the integral using the trapezoid method on the samples.
int_v1 = np.trapz(v1, dx=interval)
int_v2 = np.trapz(v2, dx=interval)
# Calculate the average improvement.
avg_exp_diff = (int_v2 - int_v1) / (max_int - min_int)
except (TypeError, ZeroDivisionError, ValueError, np.RankWarning) as e: return 0
# Convert to a percentage.
avg_diff = (math.exp(avg_exp_diff) - 1) * 100
return avg_diff
def FillForm(string_for_substitution, dictionary_of_vars): """
This function substitutes all matches of the command string //%% ... %%// with the variable represented by ... . """
return_string = string_for_substitution for i in re.findall("//%%(.*)%%//", string_for_substitution):
return_string = re.sub("//%%" + i + "%%//", dictionary_of_vars[i],
return_string) return return_string
def HasMetrics(line): """
The metrics files produced by aomenc are started with a B for headers. """ # If the first char of the first word on the line is a digit if len(line) == 0: returnFalse if len(line.split()) == 0: returnFalse if line.split()[0][0:1].isdigit(): returnTrue returnFalse
def ParseMetricFile(file_name, metric_column):
metric_set1 = set([])
metric_file = open(file_name, "r") for line in metric_file:
metrics = string.split(line) if HasMetrics(line): if metric_column < len(metrics): try:
tuple = float(metrics[0]), float(metrics[metric_column]) except:
tuple = float(metrics[0]), 0 else:
tuple = float(metrics[0]), 0
metric_set1.add(tuple)
metric_set1_sorted = sorted(metric_set1) return metric_set1_sorted
def FileBetter(file_name_1, file_name_2, metric_column, method): """
Compares two data files and determines which is better and by how
much. Also produces a histogram of how much better, by PSNR.
metric_column is the metric. """ # Store and parse our two files into lists of unique tuples.
# Read the two files, parsing out lines starting with bitrate.
metric_set1_sorted = ParseMetricFile(file_name_1, metric_column)
metric_set2_sorted = ParseMetricFile(file_name_2, metric_column)
def GraphBetter(metric_set1_sorted, metric_set2_sorted, base_is_set_2): """
Search through the sorted metric file for metrics on either side of
the metric from file 1. Since both lists are sorted we really
should not have to search through the entire range, but these
are small files."""
total_bitrate_difference_ratio = 0.0
count = 0 for bitrate, metric in metric_set1_sorted: if bitrate == 0: continue for i in range(len(metric_set2_sorted) - 1):
s2_bitrate_0, s2_metric_0 = metric_set2_sorted[i]
s2_bitrate_1, s2_metric_1 = metric_set2_sorted[i + 1] # We have a point on either side of our metric range. if metric > s2_metric_0 and metric <= s2_metric_1:
# Calculate the average improvement between graphs. if count != 0:
avg = total_bitrate_difference_ratio / count
else:
avg = 0.0
return avg
# Be fair to both graphs by testing all the points in each. if method == 'avg':
avg_improvement = 50 * (
GraphBetter(metric_set1_sorted, metric_set2_sorted, 1) -
GraphBetter(metric_set2_sorted, metric_set1_sorted, 0)) elif method == 'dsnr':
avg_improvement = bdsnr2(metric_set1_sorted, metric_set2_sorted) else:
avg_improvement = bdrate2(metric_set2_sorted, metric_set1_sorted)
return avg_improvement
def HandleFiles(variables): """
This script creates html for displaying metric data produced from data in a video stats file, as created by the AOM project when enable_psnr is turned on:
The script parses each metrics file [see below] that matches the
statfile_pattern in the baseline directory and looks for the file that
matches that same file in each of the sub_dirs, and compares the resultant
metrics bitrate, avg psnr, glb psnr, and ssim. "
It provides a table in which each row is a file in the line directory, and a column for each subdir, with the cells representing how that clip
compares to baseline for that subdir. A graph is given for each which
compares file size to that metric. If you click on a point in the graph it
zooms in on that point.
# The template file is the html file into which we will write the # data from the stats file, formatted correctly for the gviz_api.
template_file = open(variables[1], "r")
page_template = template_file.read()
template_file.close()
# This is the path match pattern for finding stats files amongst # all the other files it could be. eg: *.stt
file_pattern = variables[2]
# This is the directory with files that we will use to do the comparison # against.
baseline_dir = variables[3]
snrs = ''
filestable = {}
for metric in ['avg','dsnr','drate']:
description = {"file": ("string", "File")}
# Go through each directory and add a column header to our description.
countoverall = {}
sumoverall = {}
for directory in dirs:
description[directory] = ("number", directory)
countoverall[directory] = 0
sumoverall[directory] = 0
# Data holds the data for the visualization, name given comes from # gviz_api sample code.
data = [] for filename in dir_list:
row = {'file': splitext(basename(filename))[0] }
baseline_file_name = baseline_dir + "/" + filename
# Read the metric file from each of the directories in our list. for directory in dirs:
metric_file_name = directory + "/" + filename
# If there is a metric file in the current directory, open it # and calculate its overall difference between it and the baseline # directory's metric file. if os.path.isfile(metric_file_name):
overall = FileBetter(baseline_file_name, metric_file_name,
column, metric)
row[directory] = overall
# Now we collect all the data for all the graphs. First the column # headers which will be Datarate and then each directory.
columns = ("datarate",baseline_dir)
description = {"datarate":("number", "Datarate")} for directory in dirs:
description[directory] = ("number", directory)
# Now collect the data for the graphs, file by file. for filename in dir_list:
data = []
# Collect the file in each directory and store all of its metrics # in the associated gviz metrics table.
all_dirs = dirs + [baseline_dir] for directory in all_dirs:
# Read and parse the metrics file storing it to the data we'll # use for the gviz_api.Datatable.
metrics = ParseMetricFile(metric_file_name, column) for bitrate, metric in metrics:
data.append({"datarate": bitrate, directory: metric})
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.