📄 kdu_compress.cpp
字号:
/*****************************************************************************/// File: kdu_compress.cpp [scope = APPS/COMPRESSOR]// Version: Kakadu, V2.2// Author: David Taubman// Last Revised: 20 June, 2001/*****************************************************************************/// Copyright 2001, David Taubman, The University of New South Wales (UNSW)// The copyright owner is Unisearch Ltd, Australia (commercial arm of UNSW)// Neither this copyright statement, nor the licensing details below// may be removed from this file or dissociated from its contents./*****************************************************************************/// Licensee: Book Owner// License number: 99999// The Licensee has been granted a NON-COMMERCIAL license to the contents of// this source file, said Licensee being the owner of a copy of the book,// "JPEG2000: Image Compression Fundamentals, Standards and Practice," by// Taubman and Marcellin (Kluwer Academic Publishers, 2001). A brief summary// of the license appears below. This summary is not to be relied upon in// preference to the full text of the license agreement, which was accepted// upon breaking the seal of the compact disc accompanying the above-mentioned// book.// 1. The Licensee has the right to Non-Commercial Use of the Kakadu software,// Version 2.2, including distribution of one or more Applications built// using the software, provided such distribution is not for financial// return.// 2. The Licensee has the right to personal use of the Kakadu software,// Version 2.2.// 3. The Licensee has the right to distribute Reusable Code (including// source code and dynamically or statically linked libraries) to a Third// Party, provided the Third Party possesses a license to use the Kakadu// software, Version 2.2, and provided such distribution is not for// financial return./******************************************************************************Description: File-based JPEG2000 compressor application, demonstrating many of thecompression-oriented capabilities of the Kakadu framework.******************************************************************************/#include <string.h>#include <stdio.h> // so we can use `sscanf' for arg parsing.#include <math.h>#include <assert.h>#include <fstream>// Kakadu core includes#include "kdu_elementary.h"#include "kdu_messaging.h"#include "kdu_params.h"#include "kdu_compressed.h"#include "kdu_roi_processing.h"#include "kdu_sample_processing.h"// Application includes#include "kdu_args.h"#include "kdu_image.h"#include "kdu_file_io.h"#include "jp2.h"#include "compress_local.h"#include "roi_sources.h"/* ========================================================================= *//* Pretty Printing Version of `cout' *//* ========================================================================= */static kdu_pretty_buf pretty_cout_buf(&std::cout);static std::ostream pretty_cout(&pretty_cout_buf);/* ========================================================================= *//* Internal Functions *//* ========================================================================= *//*****************************************************************************//* STATIC print_usage *//*****************************************************************************/static void print_usage(char *prog, bool comprehensive=false){ kdu_pretty_buf strbuf(&std::cout); std::ostream out(&strbuf); out << "Usage:\n \"" << prog << " ...\n"; strbuf.set_master_indent(3); out << "-i <file 1>,...\n"; if (comprehensive) out << "\tOne or more input files. If multiple files are provided, " "they must be separated by commas. Any spaces will be treated as " "part of the file name. Currently accepted image file formats " "include RAW, BMP, PBM, PGM and PPM. For raw files, the sample " "bits must be in the least significant bit positions of an 8, 16, " "24 or 32 bit word, depending on the bit-depth. Unused MSB's in " "each word are entirely disregarded. The word organization is " "big-endian. Also, with raw files, the dimensions must be provided " "separately using `Sdims' or any other appropriate combination of " "SIZ-type parameters.\n"; out << "-o <compressed file -- raw code-stream unless suffix is \".jp2\">\n"; if (comprehensive) out << "\tName of file to receive the compressed code-stream. If the " "file name has a \".jp2\" suffix (not case sensitive), the " "code-stream will be wrapped up inside the JP2 file format. In " "this case, the first 3 source image components will be treated " "as sRGB colour channels (red, green then blue) and the remainder " "will be identified as auxiliary undefined components in the JP2 " "file. If an input file defines a colour palette (quite common " "with BMP files), this will be preserved through the JP2 file " "format and samples will be correctly de-palettized by " "conformant JP2 readers. If there are fewer than 3 components " "available (taking any palette into account), the first component " "will be identified as a luminance component with the sRGB " "gamma and any remaining component will be identified as an " "auxiliary undefined channel. Some of these default decisions " "may be overridden by subsequent command line arguments.\n"; out << "-roi {<top>,<left>},{<height>,<width>} | <PGM image>,<threshold>\n"; if (comprehensive) out << "\tEstablish a region of interest (foreground) to be coded more " "precisely and/or earlier in the progression than the rest of " "the image (background). This argument has no effect unless " "the \"Rshift\" attribute is also set. The \"Rlevels\" attribute " "may also be used to control the number of DWT levels which " "will be affected by the ROI information.\n" "\t The single parameter supplied with this " "argument may take one of two forms. The first form provides " "a simple rectangular region of interest, specified in terms of " "its upper left hand corner coordinates (comma-separated and " "enclosed in curly braces) and its dimensions (also comma-" "separated and enclosed in braces). All coordinates and " "dimensions are expressed relative to the origin and dimensions " "of the high resolution grid (or canvas), using real numbers in " "the range 0 to 1. If the original image is to be rotated during " "compression (see `-rotate'), the coordinates supplied here are " "to be interpreted with respect to the orientation of the image " "being compressed.\n" "\t The second form for the single parameter string supplied " "with the `-roi' argument involves a named (PGM) image file, " "separated by a comma from an ensuing real-valued threshold in " "the range 0 to 1. In this case, the image is scaled " "(interpolated) to fill the region occupied by each image " "component. Pixel values whose relative amplitude exceeds the " "threshold identify the foreground region.\n"; out << "-rate -|<bits/pel>,<bits/pel>,...\n"; if (comprehensive) out << "\tOne or more bit-rates, expressed in terms of the ratio between " "the total number of compressed bits (including headers) and the " "product of the largest horizontal and vertical image component " "dimensions. A dash, \"-\", may be used in place of the first " "bit-rate in the list to indicate that the final quality layer " "should include all compressed bits. Specifying a very large " "rate target is fundamentally different to using the dash, \"-\", " "because the former approach may cause the incremental rate " "allocator to discard terminal coding passes which do not lie " "on the rate-distortion convex hull. This means that reversible " "compression might not yield a truly lossless representation if " "you specify `-rate' without a dash for the first rate target, no " "matter how large the largest rate target is.\n" "\t If \"Clayers\" is not used, the number of layers is " "set to the number of rates specified here. If \"Clayers\" is used " "to specify an actual number of quality layers, one of the " "following must be true: 1) the number of rates specified here is " "identical to the specified number of layers; or 2) one, two or no " "rates are specified using this argument. When two rates are " "specified, the number of layers must be 2 or more and intervening " "layers will be assigned roughly logarithmically spaced bit-rates. " "When only one rate is specified, an internal heuristic determines " "a lower bound and logarithmically spaces the layer rates over the " "range.\n"; out << "-slope <layer slope>,<layer slope>,...\n"; if (comprehensive) out << "\tIf present, this argument provides rate control information " "directly in terms of distortion-length slope values, overriding " "any information which may or may not have been supplied via a " "`-rate' argument. If the number of quality layers is not " "specified via a `Qlayers' argument, it will be deduced from the " "number of slope values. Slopes are inversely related to " "bit-rate, so the slopes should decrease from layer to layer. The " "program automatically sorts slopes into decreasing order so you " "need not worry about getting the order right. For reference " "we note that a slope value of 0 means that all compressed bits " "will be included by the end of the relevant layer, while a " "slope value of 65535 means that no compressed bits will be " "included in the layer.\n"; out << "-full -- forces encoding and storing of all bit-planes.\n"; if (comprehensive) out << "\tBy default, the system incrementally constructs conservative " "estimates of the final rate allocation parameters and uses these " "to skip coding passes which are very likely to be discarded " "during rate allocation. It also discards any compressed " "code-bytes which we know we will not be needing on a regular " "basis, so as to conserve memory. For large images, the memory " "consumption can approach the final compressed file size. You " "might like to use the `-full' argument if you are compressing " "an image with highly non-uniform statistics.\n"; out << "-precise -- forces the use of 32-bit representations.\n"; if (comprehensive) out << "\tBy default, 16-bit data representations will be employed for " "sample data processing operations (colour transform and DWT) " "whenever the image component bit-depth is sufficiently small.\n"; out << "-no_weights -- target MSE minimization for colour images.\n"; if (comprehensive) out << "\tBy default, visual weights will be automatically used for " "colour imagery (anything with 3 compatible components). Turn " "this off if you want direct minimization of the MSE over all " "reconstructed colour components.\n"; out << "-no_palette\n"; if (comprehensive) out << "\tThis argument is meaningful only when reading palettized " "imagery and compressing to a JP2 file. By default, the " "palette will be preserved in the JP2 file and only the " "palette indices will be compressed. In many cases, it may " "be more efficient to compress the RGB data as a 24-bit " "continuous tone image. To make sure that this happens, select " "the `-no_palette' option.\n"; out << "-jp2_space <sLUM|sRGB|sYCC|iccLUM|iccRGB>[,<parameters>]\n"; if (comprehensive) out << "\tIdentifies the number of colour channels and the type of " "colour space. The argument is illegal except when the output " "file has the \".jp2\" suffix, as explained above. The argument " "must be followed by a single string consisting of one of the 5 " "colour space names, possibly followed by a comma-separated list " "of parameters.\n" "\t If the space is \"iccLUM\", two parameters must " "follow, `gamma' and `beta', which identify the tone reproduction " "curve. As examples, the sRGB space has gamma=2.4 and beta=0.055, " "while NTSC RGB has gammma=2.2 and beta=0.099. A pure power law " "has beta=0, but is not recommended due to the ill-conditioned " "nature of the resulting function around 0.\n" "\t If the space is \"iccRGB\", 11 parameters must follow in " "the comma separated list. The first two of these are the gamma " "and beta values, as above. The next 9 parameters hold the X,Y,Z " "coordinates (nominally in the range 0 to 1) of the three colour " "channels, after undoing the gamma compensation to obtain a " "linear representation. The first three parameters hold the X " "coordinates of the red, green and blue channels, respectively. " "The the next three parameters hold the Y coordinates and the " "last three parameters hold the Z coordinates. Note that the " "XYZ representation should be adjusted for the desired appearance " "under CIE D50 illuminant.\n"; out << "-jp2_aspect <aspect ratio of high-res canvas grid>\n"; if (comprehensive) out << "\tIdentifies the aspect ratio to be used by a conformant JP2 " "reader when rendering the decompressed image to a display, " "printer or other output device. The aspect ratio identifies " "ratio formed by dividing the vertical grid spacing by the " "horizontal grid spacing, where the relevant grid is that of the " "high resolution canvas. Sub-sampling factors determine the " "number of high resolution canvas grid points occupied by any " "given image component sample in each direction. By " "default conformant JP2 readers are expected to assume a 1:1 " "aspect ratio on the high resolution canvas, so that the use of " "non-identical sub-sampling factors for an image component " "implies a required aspect ratio conversion after decompression.\n"; out << "-rotate <degrees>\n"; if (comprehensive) out << "\tRotate source image prior to compression. " "Must be multiple of 90 degrees.\n"; siz_params siz; siz.describe_strings(out,comprehensive); cod_params cod; cod.describe_strings(out,comprehensive); qcd_params qcd; qcd.describe_strings(out,comprehensive); rgn_params rgn; rgn.describe_strings(out,comprehensive); poc_params poc; poc.describe_strings(out,comprehensive); crg_params crg; crg.describe_strings(out,comprehensive); out << "-cpu <coder-iterations>\n"; if (comprehensive) out << "\tTimes end-to-end execution and, optionally, the block encoding " "operation, reporting throughput statistics. If " "`coder-iterations' is 0, the block coder will not be timed, " "leading to the most accurate end-to-end system execution " "times. Otherwise, `coder-iterations' must be a positive " "integer -- larger values will result in more accurate " "estimates of the block encoder processing time, but " "degrade the accuracy of end-to-end system execution time " "estimates. Note that end-to-end times include the impact " "of image file reading, which can be considerable.\n"; out << "-mem -- Report memory usage.\n"; out << "-s <switch file>\n"; if (comprehensive) out << "\tSwitch to reading arguments from a file. In the file, argument " "strings are separated by whitespace characters, including spaces, " "tabs and new-line characters. Comments may be included by " "introducing a `#' or a `%' character, either of which causes " "the remainder of the line to be discarded. Any number of " "\"-s\" argument switch commands may be included on the command " "line.\n"; out << "-record <file>\n"; if (comprehensive) out << "\tRecord code-stream parameters in a file, using the same format " "which is accepted when specifying the parameters on the command " "line.\n"; out << "-quiet -- suppress informative messages.\n"; out << "-usage -- print a comprehensive usage statement.\n"; out << "-u -- print a brief usage statement.\"\n\n"; if (!comprehensive) { out.flush(); exit(0); } strbuf.set_master_indent(0); out << "Notes:\n"; strbuf.set_master_indent(3); out << " Arguments which commence with an upper case letter (rather than " "a dash) are used to set up code-stream parameter attributes. " "These arguments have the general form:" " <arg name>={fld1,fld2,...},{fld1,fld2,...},..., " "where curly braces enclose records and each record is composed of " "fields. The type and acceptable values for the fields are " "identified in the usage statements, along with whether or not " "multiple records are allowed. In the special case where only one " "field is defined per record, the curly braces may be omitted. " "In no event may any spaces appear inside an attribute argument.\n"; out << " Most of the code-stream parameter attributes take an optional " "tile-component modifier, consisting of a colon, followed by a " "tile specifier, a component specifier, or both. The tile specifier " "consists of the letter `T', followed immediately be the tile index " "(tiles are numbered in raster order, starting from 0). Similarly, " "the component specifier consists of the letter `C', followed " "immediately by the component index (starting from 0). These " "modifiers may be used to specify parameter changes in specific " "tiles, components, or tile-components.\n"; out << " If you do not remember the exact form or description of one of " "the code-stream attribute arguments, simply give the attribute name " "on the command-line and the program will exit with a detailed " "description of the attribute.\n"; out << " If SIZ parameters are to be supplied explicitly on the " "command line, be aware that these may be affected by simultaneous " "specification of geometric transformations. If uncertain of the " "behaviour, use `-record' to determine the final compressed " "code-stream parameters which were used.\n"; out << " If you are compressing a 3 component image using the " "reversible or irreversible colour transform (this is the default), " "the program will automatically introduce a reasonable set of visual " "weighting factors, unless you use the \"Clev_weights\" or " "\"Cband_weights\" options yourself. This does not happen " "automatically in the case of single component images, which are " "optimized purely for MSE by default. To see whether weighting " "factors were used, you may like to use the `-record' option.\n"; out.flush(); exit(0);}/*****************************************************************************//* STATIC parse_simple_args *//*****************************************************************************/static kdc_file_binding * parse_simple_args(kdu_args &args, char * &ofname, std::ostream * &record_stream, bool &transpose, bool &vflip, bool &hflip, bool &allow_rate_prediction, bool &allow_shorts, bool &no_weights, bool &no_palette, int &cpu_iterations, bool &mem, bool &quiet) /* Parses most simple arguments (those involving a dash). Most parameters are returned via the reference arguments, with the exception of the input file names, which are returned via a linked list of `kdc_file_binding' objects. Only the `fname' field of each `kdc_file_binding' record is filled out here. The value returned via `cpu_iterations' is negative unless CPU times are required. */{ int rotate; kdc_file_binding *files, *last_file, *new_file; if ((args.get_first() == NULL) || (args.find("-u") != NULL)) print_usage(args.get_prog_name()); if (args.find("-usage") != NULL) print_usage(args.get_prog_name(),true); files = last_file = NULL; ofname = NULL;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -