/// <summary> Ctor resamples a BlkImgDataSrc so that all components /// have the same number of samples. /// /// Note the present implementation does only two to one /// respampling in either direction (row, column). /// /// </summary> /// <param name="src">-- Source of image data /// </param> /// <param name="csm">-- provides colorspace info /// </param> protected internal Resampler(BlkImgDataSrc src, ColorSpace csMap) : base(src, csMap) { int c; // Calculate the minimum and maximum subsampling factor // across all channels. int minX = src.getCompSubsX(0); int minY = src.getCompSubsY(0); int maxX = minX; int maxY = minY; for (c = 1; c < ncomps; ++c) { minX = System.Math.Min(minX, src.getCompSubsX(c)); minY = System.Math.Min(minY, src.getCompSubsY(c)); maxX = System.Math.Max(maxX, src.getCompSubsX(c)); maxY = System.Math.Max(maxY, src.getCompSubsY(c)); } // Throw an exception for other than 2:1 sampling. if ((maxX != 1 && maxX != 2) || (maxY != 1 && maxY != 2)) { throw new ColorSpaceException("Upsampling by other than 2:1 not" + " supported"); } minCompSubsX = minX; minCompSubsY = minY; maxCompSubsX = maxX; maxCompSubsY = maxY; /* end Resampler ctor */ }
/// <summary> Creates a new writer to the specified File object, to write data from /// the specified component. /// /// <p>The size of the image that is written to the file is the size of the /// component from which to get the data, specified by b, not the size of /// the source image (they differ if there is some sub-sampling).</p> /// /// </summary> /// <param name="out">The file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="c">The index of the component from where to get the data. /// /// </param> public ImgWriterPGM(IFileInfo out_Renamed, BlkImgDataSrc imgSrc, int c) { // Check that imgSrc is of the correct type // Check that the component index is valid if (c < 0 || c >= imgSrc.NumComps) { throw new System.ArgumentException("Invalid number of components"); } // Check that imgSrc is of the correct type if (imgSrc.getNomRangeBits(c) > 8) { FacilityManager.getMsgLogger().println("Warning: Component " + c + " has nominal bitdepth " + imgSrc.getNomRangeBits(c) + ". Pixel values will be " + "down-shifted to fit bitdepth of 8 for PGM file", 8, 8); } // Initialize if (out_Renamed.Exists && !out_Renamed.Delete()) { throw new System.IO.IOException("Could not reset file"); } this.out_Renamed = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(out_Renamed, "rw"); src = imgSrc; this.c = c; w = imgSrc.ImgWidth; h = imgSrc.ImgHeight; fb = imgSrc.getFixedPoint(c); levShift = 1 << (imgSrc.getNomRangeBits(c) - 1); writeHeaderInfo(); }
/// <summary> Ctor resamples a BlkImgDataSrc so that all components /// have the same number of samples. /// /// Note the present implementation does only two to one /// respampling in either direction (row, column). /// /// </summary> /// <param name="src">-- Source of image data /// </param> /// <param name="csm">-- provides colorspace info /// </param> protected internal Resampler(BlkImgDataSrc src, ColorSpace csMap):base(src, csMap) { int c; // Calculate the minimum and maximum subsampling factor // across all channels. int minX = src.getCompSubsX(0); int minY = src.getCompSubsY(0); int maxX = minX; int maxY = minY; for (c = 1; c < ncomps; ++c) { minX = System.Math.Min(minX, src.getCompSubsX(c)); minY = System.Math.Min(minY, src.getCompSubsY(c)); maxX = System.Math.Max(maxX, src.getCompSubsX(c)); maxY = System.Math.Max(maxY, src.getCompSubsY(c)); } // Throw an exception for other than 2:1 sampling. if ((maxX != 1 && maxX != 2) || (maxY != 1 && maxY != 2)) { throw new ColorSpaceException("Upsampling by other than 2:1 not" + " supported"); } minCompSubsX = minX; minCompSubsY = minY; maxCompSubsX = maxX; maxCompSubsY = maxY; /* end Resampler ctor */ }
/// <summary> Constructs a new tiler with the specified 'BlkImgDataSrc' source, /// image origin, tiling origin and nominal tile size. /// /// </summary> /// <param name="src">The 'BlkImgDataSrc' source from where to get the image /// data. It must not be tiled and the image origin must be at '(0,0)' on /// its canvas. /// /// </param> /// <param name="ax">The horizontal coordinate of the image origin in the canvas /// system, on the reference grid (i.e. the image's top-left corner in the /// reference grid). /// /// </param> /// <param name="ay">The vertical coordinate of the image origin in the canvas /// system, on the reference grid (i.e. the image's top-left corner in the /// reference grid). /// /// </param> /// <param name="px">The horizontal tiling origin, in the canvas system, on the /// reference grid. It must satisfy 'px<=ax'. /// /// </param> /// <param name="py">The vertical tiling origin, in the canvas system, on the /// reference grid. It must satisfy 'py<=ay'. /// /// </param> /// <param name="nw">The nominal tile width, on the reference grid. If 0 then /// there is no tiling in that direction. /// /// </param> /// <param name="nh">The nominal tile height, on the reference grid. If 0 then /// there is no tiling in that direction. /// /// </param> /// <exception cref="IllegalArgumentException">If src is tiled or "canvased", or /// if the arguments do not satisfy the specified constraints. /// /// </exception> public Tiler(BlkImgDataSrc src, int ax, int ay, int px, int py, int nw, int nh) : base(src) { // Initialize this.src = src; this.x0siz = ax; this.y0siz = ay; this.xt0siz = px; this.yt0siz = py; this.xtsiz = nw; this.ytsiz = nh; // Verify that input is not tiled if (src.getNumTiles() != 1) { throw new System.ArgumentException("Source is tiled"); } // Verify that source is not "canvased" if (src.ImgULX != 0 || src.ImgULY != 0) { throw new System.ArgumentException("Source is \"canvased\""); } // Verify that arguments satisfy trivial requirements if (x0siz < 0 || y0siz < 0 || xt0siz < 0 || yt0siz < 0 || xtsiz < 0 || ytsiz < 0 || xt0siz > x0siz || yt0siz > y0siz) { throw new System.ArgumentException("Invalid image origin, " + "tiling origin or nominal " + "tile size"); } // If no tiling has been specified, creates a unique tile with maximum // dimension. if (xtsiz == 0) { xtsiz = x0siz + src.ImgWidth - xt0siz; } if (ytsiz == 0) { ytsiz = y0siz + src.ImgHeight - yt0siz; } // Automatically adjusts xt0siz,yt0siz so that tile (0,0) always // overlaps with the image. if (x0siz - xt0siz >= xtsiz) { xt0siz += ((x0siz - xt0siz) / xtsiz) * xtsiz; } if (y0siz - yt0siz >= ytsiz) { yt0siz += ((y0siz - yt0siz) / ytsiz) * ytsiz; } if (x0siz - xt0siz >= xtsiz || y0siz - yt0siz >= ytsiz) { FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.INFO, "Automatically adjusted tiling " + "origin to equivalent one (" + xt0siz + "," + yt0siz + ") so that " + "first tile overlaps the image"); } // Calculate the number of tiles //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" ntX = (int)System.Math.Ceiling((x0siz + src.ImgWidth) / (double)xtsiz); //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" ntY = (int)System.Math.Ceiling((y0siz + src.ImgHeight) / (double)ytsiz); }
/// <summary> Ctor which creates an ICCProfile for the image and initializes /// all data objects (input, working, and output). /// /// </summary> /// <param name="src">-- Source of image data /// </param> /// <param name="csm">-- provides colorspace info /// /// </param> protected internal ColorSpaceMapper(BlkImgDataSrc src, ColorSpace csMap) : base(src) { InitBlock(); this.src = src; this.csMap = csMap; initialize(); /* end ColorSpaceMapper ctor */ }
/// <summary> Constructs a new ForwCompTransf object that operates on the /// specified source of image data. /// /// </summary> /// <param name="imgSrc">The source from where to get the data to be /// transformed /// /// </param> /// <param name="decSpec">The decoder specifications /// /// </param> /// <param name="utdepth">The bit depth of the un-transformed components /// /// </param> /// <param name="pl">The command line optinons of the decoder /// /// </param> /// <seealso cref="BlkImgDataSrc"> /// /// </seealso> public InvCompTransf(BlkImgDataSrc imgSrc, DecoderSpecs decSpec, int[] utdepth, ParameterList pl) : base(imgSrc) { this.cts = decSpec.cts; this.wfs = decSpec.wfs; src = imgSrc; this.utdepth = utdepth; noCompTransf = !(pl.getBooleanParameter("comp_transf")); }
/// <summary> Creates a new writer to the specified File object, to write data from /// the specified component. /// /// <p>The size of the image that is written to the file is the size of the /// component from which to get the data, specified by b, not the size of /// the source image (they differ if there is some sub-sampling).</p> /// /// <p>All the header informations are given by the BlkImgDataSrc source /// (component width, component height, bit-depth) and sign flag, which are /// provided to the constructor. The endianness is always big-endian (MSB /// first).</p> /// /// </summary> /// <param name="out">The file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="c">The index of the component from where to get the data. /// /// </param> /// <param name="isSigned">Whether the datas are signed or not (needed only when /// writing header). /// /// </param> /// <seealso cref="DataBlk"> /// /// </seealso> public ImgWriterPGX(IFileInfo out_Renamed, BlkImgDataSrc imgSrc, int c, bool isSigned) { //Initialize this.c = c; if (out_Renamed.Exists && !out_Renamed.Delete()) { throw new System.IO.IOException("Could not reset file"); } this.out_Renamed = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(out_Renamed, "rw"); this.isSigned = isSigned; src = imgSrc; w = src.ImgWidth; h = src.ImgHeight; fb = imgSrc.getFixedPoint(c); bitDepth = src.getNomRangeBits(this.c); if ((bitDepth <= 0) || (bitDepth > 31)) { throw new System.IO.IOException("PGX supports only bit-depth between " + "1 and 31"); } if (bitDepth <= 8) { packBytes = 1; } else if (bitDepth <= 16) { packBytes = 2; } else { // <= 31 packBytes = 4; } // Writes PGX header System.String tmpString = "PG " + "ML " + ((this.isSigned)?"- ":"+ ") + bitDepth + " " + w + " " + h + "\n"; // component height byte[] tmpByte = System.Text.Encoding.UTF8.GetBytes(tmpString); for (int i = 0; i < tmpByte.Length; i++) { this.out_Renamed.WriteByte((byte)tmpByte[i]); } offset = tmpByte.Length; maxVal = this.isSigned?((1 << (src.getNomRangeBits(c) - 1)) - 1):((1 << src.getNomRangeBits(c)) - 1); minVal = this.isSigned?((-1) * (1 << (src.getNomRangeBits(c) - 1))):0; levShift = (this.isSigned)?0:1 << (src.getNomRangeBits(c) - 1); }
/// <summary> Ctor which creates an ICCProfile for the image and initializes /// all data objects (input, working, output). /// /// </summary> /// <param name="src">-- Source of image data /// </param> /// <param name="csm">-- provides colorspace info /// /// </param> /// <exception cref="IOException"> /// </exception> /// <exception cref="ICCProfileException"> /// </exception> /// <exception cref="IllegalArgumentException"> /// </exception> protected internal ICCProfiler(BlkImgDataSrc src, CSJ2K.Color.ColorSpace csMap) : base(src, csMap) { initialize(); iccp = getICCProfile(csMap); if (ncomps == 1) { xform = new MonochromeTransformTosRGB(iccp, maxValueArray[0], shiftValueArray[0]); } else { xform = new MatrixBasedTransformTosRGB(iccp, maxValueArray, shiftValueArray); } /* end ICCProfiler ctor */ }
/// <summary> Initialize all members with the given number of tiles and components /// and the command-line arguments stored in a ParameterList instance /// /// </summary> /// <param name="nt">Number of tiles /// /// </param> /// <param name="nc">Number of components /// /// </param> /// <param name="imgsrc">The image source (used to get the image size) /// /// </param> /// <param name="pl">The ParameterList instance /// /// </param> public EncoderSpecs(int nt, int nc, BlkImgDataSrc imgsrc, ParameterList pl) { nTiles = nt; nComp = nc; // ROI rois = new MaxShiftSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP); // Quantization pl.checkList(Quantizer.OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(Quantizer.ParameterInfo)); qts = new QuantTypeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl); qsss = new QuantStepSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl); gbs = new GuardBitsSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl); // Wavelet transform wfs = new AnWTFilterSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, qts, pl); dls = new IntegerSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl, "Wlev"); // Component transformation cts = new ForwCompTransfSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE, wfs, pl); // Entropy coder System.String[] strLcs = new System.String[] { "near_opt", "lazy_good", "lazy" }; lcs = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Clen_calc", strLcs, pl); System.String[] strTerm = new System.String[] { "near_opt", "easy", "predict", "full" }; tts = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cterm_type", strTerm, pl); System.String[] strBoolean = new System.String[] { "on", "off" }; sss = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cseg_symbol", strBoolean, pl); css = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Ccausal", strBoolean, pl); rts = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cterminate", strBoolean, pl); mqrs = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "CresetMQ", strBoolean, pl); bms = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cbypass", strBoolean, pl); cblks = new CBlkSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl); // Precinct partition pss = new PrecinctSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, imgsrc, dls, pl); // Codestream sops = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE, "Psop", strBoolean, pl); ephs = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE, "Peph", strBoolean, pl); }
/// <summary> Factory method for creating instances of this class.</summary> /// <param name="src">-- source of image data /// </param> /// <param name="csMap">-- provides colorspace info /// </param> /// <returns> ColorSpaceMapper instance /// </returns> /// <exception cref="IOException">profile access exception /// </exception> public static BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) { // Check parameters csMap.pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo)); // Perform ICCProfiling or ColorSpace tranfsormation. if (csMap.Method == ColorSpace.MethodEnum.ICC_PROFILED) { return(ICCProfiler.createInstance(src, csMap)); } else { ColorSpace.CSEnum colorspace = csMap.getColorSpace(); if (colorspace == ColorSpace.CSEnum.sRGB) { return(EnumeratedColorSpaceMapper.createInstance(src, csMap)); } else if (colorspace == ColorSpace.CSEnum.GreyScale) { return(EnumeratedColorSpaceMapper.createInstance(src, csMap)); } else if (colorspace == ColorSpace.CSEnum.sYCC) { return(SYccColorSpaceMapper.createInstance(src, csMap)); } if (colorspace == ColorSpace.CSEnum.esRGB) { return(EsRgbColorSpaceMapper.createInstance(src, csMap)); } else if (colorspace == ColorSpace.CSEnum.Unknown) { return(null); } else { throw new ColorSpaceException("Bad color space specification in image"); } } }
/// <summary> Creates a new writer to the specified File object, to write data from /// the specified component. /// /// <p>The three components that will be written as R, G and B must be /// specified through the b1, b2 and b3 arguments.</p> /// /// </summary> /// <param name="out">The file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="n1">The index of the first component from where to get the data, /// that will be written as the red channel. /// /// </param> /// <param name="n2">The index of the second component from where to get the data, /// that will be written as the green channel. /// /// </param> /// <param name="n3">The index of the third component from where to get the data, /// that will be written as the green channel. /// /// </param> /// <seealso cref="DataBlk"> /// /// </seealso> public ImgWriterPPM(IFileInfo out_Renamed, BlkImgDataSrc imgSrc, int n1, int n2, int n3) { // Check that imgSrc is of the correct type // Check that the component index is valid if ((n1 < 0) || (n1 >= imgSrc.NumComps) || (n2 < 0) || (n2 >= imgSrc.NumComps) || (n3 < 0) || (n3 >= imgSrc.NumComps) || (imgSrc.getNomRangeBits(n1) > 8) || (imgSrc.getNomRangeBits(n2) > 8) || (imgSrc.getNomRangeBits(n3) > 8)) { throw new System.ArgumentException("Invalid component indexes"); } // Initialize w = imgSrc.getCompImgWidth(n1); h = imgSrc.getCompImgHeight(n1); // Check that all components have same width and height if (w != imgSrc.getCompImgWidth(n2) || w != imgSrc.getCompImgWidth(n3) || h != imgSrc.getCompImgHeight(n2) || h != imgSrc.getCompImgHeight(n3)) { throw new System.ArgumentException("All components must have the" + " same dimensions and no" + " subsampling"); } w = imgSrc.ImgWidth; h = imgSrc.ImgHeight; // Continue initialization if (out_Renamed.Exists && !out_Renamed.Delete()) { throw new System.IO.IOException("Could not reset file"); } this.out_Renamed = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(out_Renamed, "rw"); src = imgSrc; cps[0] = n1; cps[1] = n2; cps[2] = n3; fb[0] = imgSrc.getFixedPoint(n1); fb[1] = imgSrc.getFixedPoint(n2); fb[2] = imgSrc.getFixedPoint(n3); levShift[0] = 1 << (imgSrc.getNomRangeBits(n1) - 1); levShift[1] = 1 << (imgSrc.getNomRangeBits(n2) - 1); levShift[2] = 1 << (imgSrc.getNomRangeBits(n3) - 1); writeHeaderInfo(); }
/// <summary> Initializes this object with the given source of image data and with /// all the decompositon parameters /// /// </summary> /// <param name="src">From where the image data should be obtained. /// /// </param> /// <param name="encSpec">The encoder specifications /// /// </param> /// <param name="cb0x">The horizontal coordinate of the code-block partition /// origin on the reference grid. /// /// </param> /// <param name="cb0y">The vertical coordinate of the code-block partition origin /// on the reference grid. /// /// </param> /// <seealso cref="ForwardWT"> /// /// </seealso> public ForwWTFull(BlkImgDataSrc src, EncoderSpecs encSpec, int cb0x, int cb0y) : base(src) { this.src = src; this.cb0x = cb0x; this.cb0y = cb0y; this.dls = encSpec.dls; this.filters = encSpec.wfs; this.cblks = encSpec.cblks; this.pss = encSpec.pss; int ncomp = src.NumComps; int ntiles = src.getNumTiles(); currentSubband = new SubbandAn[ncomp]; decomposedComps = new DataBlk[ncomp]; subbTrees = new SubbandAn[ntiles][]; for (int i = 0; i < ntiles; i++) { subbTrees[i] = new SubbandAn[ncomp]; } lastn = new int[ncomp]; lastm = new int[ncomp]; }
/// <summary> Factory method for creating instances of this class.</summary> /// <param name="src">-- source of image data /// </param> /// <param name="csMap">-- provides colorspace info /// </param> /// <returns> ChannelDefinitionMapper instance /// </returns> /// <exception cref="ColorSpaceException"> /// </exception> public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) { return new ChannelDefinitionMapper(src, csMap); }
/// <summary> Constructs a new ForwCompTransf object that operates on the specified /// source of image data. /// /// </summary> /// <param name="imgSrc">The source from where to get the data to be transformed /// /// </param> /// <param name="encSpec">The encoder specifications /// /// </param> /// <seealso cref="BlkImgDataSrc"> /// /// </seealso> public ForwCompTransf(BlkImgDataSrc imgSrc, EncoderSpecs encSpec) : base(imgSrc) { this.cts = encSpec.cts; this.wfs = encSpec.wfs; src = imgSrc; }
/// <summary> Factory method for creating instances of this class.</summary> /// <param name="src">-- source of image data /// </param> /// <param name="csMap">-- provides colorspace info /// </param> /// <returns> ICCProfiler instance /// </returns> /// <exception cref="IOException">profile access exception /// </exception> /// <exception cref="ICCProfileException">profile content exception /// </exception> public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, CSJ2K.Color.ColorSpace csMap) { return(new ICCProfiler(src, csMap)); }
/// <summary> Factory method for creating instances of this class.</summary> /// <param name="src">-- source of image data /// </param> /// <param name="csMap">-- provides colorspace info /// </param> /// <returns> ChannelDefinitionMapper instance /// </returns> /// <exception cref="ColorSpaceException"> /// </exception> public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) { return(new ChannelDefinitionMapper(src, csMap)); }
/// <summary> Ctor which creates an ICCProfile for the image and initializes /// all data objects (input, working, and output). /// /// </summary> /// <param name="src">-- Source of image data /// </param> /// <param name="csm">-- provides colorspace info /// </param> protected internal PalettizedColorSpaceMapper(BlkImgDataSrc src, ColorSpace csMap) : base(src, csMap) { pbox = csMap.PaletteBox; initialize(); }
/// <summary> Creates a new writer to the specified file, to write data from the /// specified component. /// /// <p>The size of the image that is written to the file is the size of the /// component from which to get the data, specified by b, not the size of /// the source image (they differ if there is some sub-sampling).</p> /// /// <p>All header information is given by the BlkImgDataSrc source /// (component width, component height, bit-depth) and sign flag, which are /// provided to the constructor. The endianness is always big-endian (MSB /// first). /// /// </summary> /// <param name="fname">The name of the file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="c">The index of the component from where to get the data. /// /// </param> /// <param name="isSigned">Whether the datas are signed or not (needed only when /// writing header). /// /// </param> /// <seealso cref="DataBlk"> /// /// </seealso> public ImgWriterPGX(System.String fname, BlkImgDataSrc imgSrc, int c, bool isSigned) : this(FileInfoFactory.New(fname), imgSrc, c, isSigned) { }
/// <summary> Factory method for creating instances of this class.</summary> /// <param name="src">-- source of image data /// </param> /// <param name="csMap">-- provides colorspace info /// </param> /// <returns> Resampler instance /// </returns> public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) { return(new Resampler(src, csMap)); }
/// <summary> Creates a new writer to the specified File object, to write data from /// the specified component. /// /// <p>The size of the image that is written to the file is the size of the /// component from which to get the data, specified by b, not the size of /// the source image (they differ if there is some sub-sampling).</p> /// /// </summary> /// <param name="out">The file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="c">The index of the component from where to get the data. /// /// </param> public ImgWriterPGM(IFileInfo out_Renamed, BlkImgDataSrc imgSrc, int c) { // Check that imgSrc is of the correct type // Check that the component index is valid if (c < 0 || c >= imgSrc.NumComps) { throw new System.ArgumentException("Invalid number of components"); } // Check that imgSrc is of the correct type if (imgSrc.getNomRangeBits(c) > 8) { FacilityManager.getMsgLogger().println("Warning: Component " + c + " has nominal bitdepth " + imgSrc.getNomRangeBits(c) + ". Pixel values will be " + "down-shifted to fit bitdepth of 8 for PGM file", 8, 8); } // Initialize if (out_Renamed.Exists && !out_Renamed.Delete()) { throw new System.IO.IOException("Could not reset file"); } this.out_Renamed = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(out_Renamed, "rw"); src = imgSrc; this.c = c; w = imgSrc.ImgWidth; h = imgSrc.ImgHeight; fb = imgSrc.getFixedPoint(c); levShift = 1 << (imgSrc.getNomRangeBits(c) - 1); writeHeaderInfo(); }
/// <summary> Class constructor. Each input BlkImgDataSrc and its component index /// must appear in the order wanted for the output components.<br> /// /// <u>Example:</u> Reading R,G,B components from 3 PGM files.<br> /// <tt> /// BlkImgDataSrc[] idList = <br> /// {<br> /// new ImgReaderPGM(new BEBufferedRandomAccessFile("R.pgm", "r")),<br> /// new ImgReaderPGM(new BEBufferedRandomAccessFile("G.pgm", "r")),<br> /// new ImgReaderPGM(new BEBufferedRandomAccessFile("B.pgm", "r"))<br> /// };<br> /// int[] compIdx = {0,0,0};<br> /// ImgDataJoiner idj = new ImgDataJoiner(idList, compIdx); /// </tt> /// /// <p>Of course, the 2 arrays must have the same length (This length is /// the number of output components). The image width and height are /// definded to be the maximum values of all the input ImgData. /// /// </summary> /// <param name="imD">The list of input BlkImgDataSrc in an array. /// /// </param> /// <param name="cIdx">The component index associated with each ImgData. /// /// </param> public ImgDataJoiner(BlkImgDataSrc[] imD, int[] cIdx) { int i; int maxW, maxH; // Initializes imageData = imD; compIdx = cIdx; if (imageData.Length != compIdx.Length) throw new System.ArgumentException("imD and cIdx must have the" + " same length"); nc = imD.Length; subsX = new int[nc]; subsY = new int[nc]; // Check that no source is tiled and that the image origin is at the // canvas origin. for (i = 0; i < nc; i++) { if (imD[i].getNumTiles() != 1 || imD[i].getCompULX(cIdx[i]) != 0 || imD[i].getCompULY(cIdx[i]) != 0) { throw new System.ArgumentException("All input components must, " + "not use tiles and must " + "have " + "the origin at the canvas " + "origin"); } } // Guess component subsampling factors based on the fact that the // ceil() operation relates the reference grid size to the component's // size, through the subsampling factor. // Mhhh, difficult problem. For now just assume that one of the // subsampling factors is always 1 and that the component width is // always larger than its subsampling factor, which covers most of the // cases. We check the correctness of the solution once found to chek // out hypothesis. // Look for max width and height. maxW = 0; maxH = 0; for (i = 0; i < nc; i++) { if (imD[i].getCompImgWidth(cIdx[i]) > maxW) maxW = imD[i].getCompImgWidth(cIdx[i]); if (imD[i].getCompImgHeight(cIdx[i]) > maxH) maxH = imD[i].getCompImgHeight(cIdx[i]); } // Set the image width and height as the maximum ones w = maxW; h = maxH; // Now get the sumsampling factors and check the subsampling factors, // just to see if above hypothesis were correct. for (i = 0; i < nc; i++) { // This calculation only holds if the subsampling factor is less // than the component width subsX[i] = (maxW + imD[i].getCompImgWidth(cIdx[i]) - 1) / imD[i].getCompImgWidth(cIdx[i]); subsY[i] = (maxH + imD[i].getCompImgHeight(cIdx[i]) - 1) / imD[i].getCompImgHeight(cIdx[i]); if ((maxW + subsX[i] - 1) / subsX[i] != imD[i].getCompImgWidth(cIdx[i]) || (maxH + subsY[i] - 1) / subsY[i] != imD[i].getCompImgHeight(cIdx[i])) { throw new System.ApplicationException("Can not compute component subsampling " + "factors: strange subsampling."); } } }
public static byte[] ToBytes(BlkImgDataSrc imgsrc, ParameterList parameters = null) { // Initialize default parameters ParameterList defpl = GetDefaultEncoderParameterList(encoder_pinfo); // Create parameter list using defaults ParameterList pl = parameters ?? new ParameterList(defpl); bool useFileFormat = false; bool pphTile = false; bool pphMain = false; bool tempSop = false; bool tempEph = false; // **** Get general parameters **** if (pl.getParameter("file_format").Equals("on")) { useFileFormat = true; if (pl.getParameter("rate") != null && pl.getFloatParameter("rate") != defpl.getFloatParameter("rate")) { warning("Specified bit-rate applies only on the codestream but not on the whole file."); } } if (pl.getParameter("tiles") == null) { error("No tiles option specified", 2); return null; } if (pl.getParameter("pph_tile").Equals("on")) { pphTile = true; if (pl.getParameter("Psop").Equals("off")) { pl["Psop"] = "on"; tempSop = true; } if (pl.getParameter("Peph").Equals("off")) { pl["Peph"] = "on"; tempEph = true; } } if (pl.getParameter("pph_main").Equals("on")) { pphMain = true; if (pl.getParameter("Psop").Equals("off")) { pl["Psop"] = "on"; tempSop = true; } if (pl.getParameter("Peph").Equals("off")) { pl["Peph"] = "on"; tempEph = true; } } if (pphTile && pphMain) error("Can't have packed packet headers in both main and" + " tile headers", 2); if (pl.getBooleanParameter("lossless") && pl.getParameter("rate") != null && pl.getFloatParameter("rate") != defpl.getFloatParameter("rate")) throw new ArgumentException("Cannot use '-rate' and " + "'-lossless' option at " + " the same time."); if (pl.getParameter("rate") == null) { error("Target bitrate not specified", 2); return null; } float rate; try { rate = pl.getFloatParameter("rate"); if (rate == -1) { rate = float.MaxValue; } } catch (FormatException e) { error("Invalid value in 'rate' option: " + pl.getParameter("rate"), 2); return null; } int pktspertp; try { pktspertp = pl.getIntParameter("tile_parts"); if (pktspertp != 0) { if (pl.getParameter("Psop").Equals("off")) { pl["Psop"] = "on"; tempSop = true; } if (pl.getParameter("Peph").Equals("off")) { pl["Peph"] = "on"; tempEph = true; } } } catch (FormatException e) { error("Invalid value in 'tile_parts' option: " + pl.getParameter("tile_parts"), 2); return null; } // **** ImgReader **** var ncomp = imgsrc.NumComps; var ppminput = imgsrc.NumComps > 1; // **** Tiler **** // get nominal tile dimensions SupportClass.StreamTokenizerSupport stok = new SupportClass.StreamTokenizerSupport(new StringReader(pl.getParameter("tiles"))); stok.EOLIsSignificant(false); stok.NextToken(); if (stok.ttype != SupportClass.StreamTokenizerSupport.TT_NUMBER) { error("An error occurred while parsing the tiles option: " + pl.getParameter("tiles"), 2); return null; } var tw = (int)stok.nval; stok.NextToken(); if (stok.ttype != SupportClass.StreamTokenizerSupport.TT_NUMBER) { error("An error occurred while parsing the tiles option: " + pl.getParameter("tiles"), 2); return null; } var th = (int)stok.nval; // Get image reference point var refs = pl.getParameter("ref").Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); int refx; int refy; try { refx = Int32.Parse(refs[0]); refy = Int32.Parse(refs[1]); } catch (IndexOutOfRangeException e) { throw new ArgumentException("Error while parsing 'ref' " + "option"); } catch (FormatException e) { throw new ArgumentException("Invalid number type in " + "'ref' option"); } if (refx < 0 || refy < 0) { throw new ArgumentException("Invalid value in 'ref' " + "option "); } // Get tiling reference point var trefs = pl.getParameter("tref").Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); int trefx; int trefy; try { trefx = Int32.Parse(trefs[0]); trefy = Int32.Parse(trefs[1]); } catch (IndexOutOfRangeException e) { throw new ArgumentException("Error while parsing 'tref' " + "option"); } catch (FormatException e) { throw new ArgumentException("Invalid number type in " + "'tref' option"); } if (trefx < 0 || trefy < 0 || trefx > refx || trefy > refy) { throw new ArgumentException("Invalid value in 'tref' " + "option "); } // Instantiate tiler Tiler imgtiler; try { imgtiler = new Tiler(imgsrc, refx, refy, trefx, trefy, tw, th); } catch (ArgumentException e) { error("Could not tile image" + ((e.Message != null) ? (":\n" + e.Message) : ""), 2); return null; } int ntiles = imgtiler.getNumTiles(); // **** Encoder specifications **** var encSpec = new EncoderSpecs(ntiles, ncomp, imgsrc, pl); // **** Component transformation **** if (ppminput && pl.getParameter("Mct") != null && pl.getParameter("Mct").Equals("off")) { FacilityManager.getMsgLogger() .printmsg( MsgLogger_Fields.WARNING, "Input image is RGB and no color transform has " + "been specified. Compression performance and " + "image quality might be greatly degraded. Use " + "the 'Mct' option to specify a color transform"); } ForwCompTransf fctransf; try { fctransf = new ForwCompTransf(imgtiler, encSpec); } catch (ArgumentException e) { error( "Could not instantiate forward component " + "transformation" + ((e.Message != null) ? (":\n" + e.Message) : ""), 2); return null; } // **** ImgDataConverter **** var converter = new ImgDataConverter(fctransf); // **** ForwardWT **** ForwardWT dwt; try { dwt = ForwardWT.createInstance(converter, pl, encSpec); } catch (ArgumentException e) { error("Could not instantiate wavelet transform" + ((e.Message != null) ? (":\n" + e.Message) : ""), 2); return null; } // **** Quantizer **** Quantizer quant; try { quant = Quantizer.createInstance(dwt, encSpec); } catch (ArgumentException e) { error("Could not instantiate quantizer" + ((e.Message != null) ? (":\n" + e.Message) : ""), 2); return null; } // **** ROIScaler **** ROIScaler rois; try { rois = ROIScaler.createInstance(quant, pl, encSpec); } catch (ArgumentException e) { error("Could not instantiate ROI scaler" + ((e.Message != null) ? (":\n" + e.Message) : ""), 2); return null; } // **** EntropyCoder **** EntropyCoder ecoder; try { ecoder = EntropyCoder.createInstance( rois, pl, encSpec.cblks, encSpec.pss, encSpec.bms, encSpec.mqrs, encSpec.rts, encSpec.css, encSpec.sss, encSpec.lcs, encSpec.tts); } catch (ArgumentException e) { error("Could not instantiate entropy coder" + ((e.Message != null) ? (":\n" + e.Message) : ""), 2); return null; } // **** CodestreamWriter **** using (var outStream = new MemoryStream()) { CodestreamWriter bwriter; try { // Rely on rate allocator to limit amount of data bwriter = new FileCodestreamWriter(outStream, Int32.MaxValue); } catch (IOException e) { error("Could not open output file" + ((e.Message != null) ? (":\n" + e.Message) : ""), 2); return null; } // **** Rate allocator **** PostCompRateAllocator ralloc; try { ralloc = PostCompRateAllocator.createInstance(ecoder, pl, rate, bwriter, encSpec); } catch (ArgumentException e) { error("Could not instantiate rate allocator" + ((e.Message != null) ? (":\n" + e.Message) : ""), 2); return null; } // **** HeaderEncoder **** var imsigned = Enumerable.Repeat(false, ncomp).ToArray(); // TODO Consider supporting signed components. var headenc = new HeaderEncoder(imgsrc, imsigned, dwt, imgtiler, encSpec, rois, ralloc, pl); ralloc.HeaderEncoder = headenc; // **** Write header to be able to estimate header overhead **** headenc.encodeMainHeader(); // **** Initialize rate allocator, with proper header // overhead. This will also encode all the data **** ralloc.initialize(); // **** Write header (final) **** headenc.reset(); headenc.encodeMainHeader(); // Insert header into the codestream bwriter.commitBitstreamHeader(headenc); // **** Now do the rate-allocation and write result **** ralloc.runAndWrite(); // **** Done **** bwriter.close(); // **** Calculate file length **** int fileLength = bwriter.Length; // **** Tile-parts and packed packet headers **** if (pktspertp > 0 || pphTile || pphMain) { try { CodestreamManipulator cm = new CodestreamManipulator( outStream, ntiles, pktspertp, pphMain, pphTile, tempSop, tempEph); fileLength += cm.doCodestreamManipulation(); //String res=""; if (pktspertp > 0) { FacilityManager.getMsgLogger() .println( "Created tile-parts " + "containing at most " + pktspertp + " packets per tile.", 4, 6); } if (pphTile) { FacilityManager.getMsgLogger().println("Moved packet headers " + "to tile headers", 4, 6); } if (pphMain) { FacilityManager.getMsgLogger().println("Moved packet headers " + "to main header", 4, 6); } } catch (IOException e) { error( "Error while creating tileparts or packed packet" + " headers" + ((e.Message != null) ? (":\n" + e.Message) : ""), 2); return null; } } // **** File Format **** if (useFileFormat) { try { int nc = imgsrc.NumComps; int[] bpc = new int[nc]; for (int comp = 0; comp < nc; comp++) { bpc[comp] = imgsrc.getNomRangeBits(comp); } outStream.Seek(0, SeekOrigin.Begin); var ffw = new FileFormatWriter( outStream, imgsrc.ImgHeight, imgsrc.ImgWidth, nc, bpc, fileLength); fileLength += ffw.writeFileFormat(); } catch (IOException e) { throw new InvalidOperationException("Error while writing JP2 file format: " + e.Message); } } // **** Close image readers *** imgsrc.close(); return outStream.ToArray(); } }
/// <summary> Creates a new writer to the specified file, to write data from the /// specified component. /// /// <p>The three components that will be written as R, G and B must be /// specified through the b1, b2 and b3 arguments.</p> /// /// </summary> /// <param name="fname">The name of the file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="n1">The index of the first component from where to get the data, /// that will be written as the red channel. /// /// </param> /// <param name="n2">The index of the second component from where to get the data, /// that will be written as the green channel. /// /// </param> /// <param name="n3">The index of the third component from where to get the data, /// that will be written as the green channel. /// /// </param> /// <seealso cref="DataBlk"> /// /// </seealso> public ImgWriterPPM(System.String fname, BlkImgDataSrc imgSrc, int n1, int n2, int n3) : this(new System.IO.FileInfo(fname), imgSrc, n1, n2, n3) { }
/// <summary> Creates a new writer to the specified file, to write data from the /// specified component. /// /// <p>The three components that will be written as R, G and B must be /// specified through the b1, b2 and b3 arguments.</p> /// /// </summary> /// <param name="fname">The name of the file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="n1">The index of the first component from where to get the data, /// that will be written as the red channel. /// /// </param> /// <param name="n2">The index of the second component from where to get the data, /// that will be written as the green channel. /// /// </param> /// <param name="n3">The index of the third component from where to get the data, /// that will be written as the green channel. /// /// </param> /// <seealso cref="DataBlk"> /// /// </seealso> public ImgWriterPPM(System.String fname, BlkImgDataSrc imgSrc, int n1, int n2, int n3):this(new System.IO.FileInfo(fname), imgSrc, n1, n2, n3) { }
/// <summary> Ctor which creates an ICCProfile for the image and initializes /// all data objects (input, working, and output). /// /// </summary> /// <param name="src">-- Source of image data /// </param> /// <param name="csm">-- provides colorspace info /// </param> protected internal ChannelDefinitionMapper(BlkImgDataSrc src, ColorSpace csMap):base(src, csMap) { /* end ChannelDefinitionMapper ctor */ }
/// <summary> Constructs a new ImgDataConverter object that operates on the specified /// source of image data. /// /// </summary> /// <param name="imgSrc">The source from where to get the data to be transformed /// /// </param> /// <param name="fp">The number of fraction bits in the casted ints /// /// </param> /// <seealso cref="BlkImgDataSrc"> /// /// </seealso> public ImgDataConverter(BlkImgDataSrc imgSrc, int fp) : base(imgSrc) { src = imgSrc; this.fp = fp; }
/// <summary> Constructs a new ForwCompTransf object that operates on the specified /// source of image data. /// /// </summary> /// <param name="imgSrc">The source from where to get the data to be transformed /// /// </param> /// <param name="encSpec">The encoder specifications /// /// </param> /// <seealso cref="BlkImgDataSrc"> /// /// </seealso> public ForwCompTransf(BlkImgDataSrc imgSrc, EncoderSpecs encSpec):base(imgSrc) { this.cts = encSpec.cts; this.wfs = encSpec.wfs; src = imgSrc; }
/// <summary> Creates a new writer to the specified file, to write data from the /// specified component. /// /// <P>The size of the image that is written to the file is the size of the /// component from which to get the data, specified by b, not the size of /// the source image (they differ if there is some sub-sampling). /// /// </summary> /// <param name="fname">The name of the file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="c">The index of the component from where to get the data. /// /// </param> public ImgWriterPGM(System.String fname, BlkImgDataSrc imgSrc, int c) : this(FileInfoFactory.New(fname), imgSrc, c) { }
/// <summary> Creates a new writer to the specified file, to write data from the /// specified component. /// /// <P>The size of the image that is written to the file is the size of the /// component from which to get the data, specified by b, not the size of /// the source image (they differ if there is some sub-sampling). /// /// </summary> /// <param name="fname">The name of the file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="c">The index of the component from where to get the data. /// /// </param> public ImgWriterPGM(System.String fname, BlkImgDataSrc imgSrc, int c) : this(FileInfoFactory.New(fname), imgSrc, c) { }
/// <summary> Ctor which creates an ICCProfile for the image and initializes /// all data objects (input, working, and output). /// /// </summary> /// <param name="src">-- Source of image data /// </param> /// <param name="csm">-- provides colorspace info /// /// </param> protected internal ColorSpaceMapper(BlkImgDataSrc src, ColorSpace csMap) : base(src) { InitBlock(); this.src = src; this.csMap = csMap; initialize(); /* end ColorSpaceMapper ctor */ }
/// <summary> Creates a new writer to the specified file, to write data from the /// specified component. /// /// <p>The size of the image that is written to the file is the size of the /// component from which to get the data, specified by b, not the size of /// the source image (they differ if there is some sub-sampling).</p> /// /// <p>All header information is given by the BlkImgDataSrc source /// (component width, component height, bit-depth) and sign flag, which are /// provided to the constructor. The endianness is always big-endian (MSB /// first). /// /// </summary> /// <param name="fname">The name of the file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="c">The index of the component from where to get the data. /// /// </param> /// <param name="isSigned">Whether the datas are signed or not (needed only when /// writing header). /// /// </param> /// <seealso cref="DataBlk"> /// /// </seealso> public ImgWriterPGX(System.String fname, BlkImgDataSrc imgSrc, int c, bool isSigned):this(new System.IO.FileInfo(fname), imgSrc, c, isSigned) { }
/// <summary> Constructs a new tiler with the specified 'BlkImgDataSrc' source, /// image origin, tiling origin and nominal tile size. /// /// </summary> /// <param name="src">The 'BlkImgDataSrc' source from where to get the image /// data. It must not be tiled and the image origin must be at '(0,0)' on /// its canvas. /// /// </param> /// <param name="ax">The horizontal coordinate of the image origin in the canvas /// system, on the reference grid (i.e. the image's top-left corner in the /// reference grid). /// /// </param> /// <param name="ay">The vertical coordinate of the image origin in the canvas /// system, on the reference grid (i.e. the image's top-left corner in the /// reference grid). /// /// </param> /// <param name="px">The horizontal tiling origin, in the canvas system, on the /// reference grid. It must satisfy 'px<=ax'. /// /// </param> /// <param name="py">The vertical tiling origin, in the canvas system, on the /// reference grid. It must satisfy 'py<=ay'. /// /// </param> /// <param name="nw">The nominal tile width, on the reference grid. If 0 then /// there is no tiling in that direction. /// /// </param> /// <param name="nh">The nominal tile height, on the reference grid. If 0 then /// there is no tiling in that direction. /// /// </param> /// <exception cref="IllegalArgumentException">If src is tiled or "canvased", or /// if the arguments do not satisfy the specified constraints. /// /// </exception> public Tiler(BlkImgDataSrc src, int ax, int ay, int px, int py, int nw, int nh):base(src) { // Initialize this.src = src; this.x0siz = ax; this.y0siz = ay; this.xt0siz = px; this.yt0siz = py; this.xtsiz = nw; this.ytsiz = nh; // Verify that input is not tiled if (src.getNumTiles() != 1) { throw new System.ArgumentException("Source is tiled"); } // Verify that source is not "canvased" if (src.ImgULX != 0 || src.ImgULY != 0) { throw new System.ArgumentException("Source is \"canvased\""); } // Verify that arguments satisfy trivial requirements if (x0siz < 0 || y0siz < 0 || xt0siz < 0 || yt0siz < 0 || xtsiz < 0 || ytsiz < 0 || xt0siz > x0siz || yt0siz > y0siz) { throw new System.ArgumentException("Invalid image origin, " + "tiling origin or nominal " + "tile size"); } // If no tiling has been specified, creates a unique tile with maximum // dimension. if (xtsiz == 0) xtsiz = x0siz + src.ImgWidth - xt0siz; if (ytsiz == 0) ytsiz = y0siz + src.ImgHeight - yt0siz; // Automatically adjusts xt0siz,yt0siz so that tile (0,0) always // overlaps with the image. if (x0siz - xt0siz >= xtsiz) { xt0siz += ((x0siz - xt0siz) / xtsiz) * xtsiz; } if (y0siz - yt0siz >= ytsiz) { yt0siz += ((y0siz - yt0siz) / ytsiz) * ytsiz; } if (x0siz - xt0siz >= xtsiz || y0siz - yt0siz >= ytsiz) { FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.INFO, "Automatically adjusted tiling " + "origin to equivalent one (" + xt0siz + "," + yt0siz + ") so that " + "first tile overlaps the image"); } // Calculate the number of tiles //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" ntX = (int) System.Math.Ceiling((x0siz + src.ImgWidth) / (double) xtsiz); //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" ntY = (int) System.Math.Ceiling((y0siz + src.ImgHeight) / (double) ytsiz); }
/// <summary> Creates a ForwardWT object with the specified filters, and with other /// options specified in the parameter list 'pl'. /// /// </summary> /// <param name="src">The source of data to be transformed /// /// </param> /// <param name="pl">The parameter list (or options). /// /// </param> /// <param name="kers">The encoder specifications. /// /// </param> /// <returns> A new ForwardWT object with the specified filters and options /// from 'pl'. /// /// </returns> /// <exception cref="IllegalArgumentException">If mandatory parameters are missing /// or if invalid values are given. /// /// </exception> public static ForwardWT createInstance(BlkImgDataSrc src, ParameterList pl, EncoderSpecs encSpec) { int deflev; // defdec removed //System.String decompstr; //System.String wtstr; //System.String pstr; //SupportClass.StreamTokenizerSupport stok; //SupportClass.Tokenizer strtok; //int prefx, prefy; // Partitioning reference point coordinates // Check parameters pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo)); deflev = ((System.Int32) encSpec.dls.getDefault()); // Code-block partition origin System.String str = ""; if (pl.getParameter("Wcboff") == null) { throw new System.ApplicationException("You must specify an argument to the '-Wcboff' " + "option. See usage with the '-u' option"); } SupportClass.Tokenizer stk = new SupportClass.Tokenizer(pl.getParameter("Wcboff")); if (stk.Count != 2) { throw new System.ArgumentException("'-Wcboff' option needs two" + " arguments. See usage with " + "the '-u' option."); } int cb0x = 0; str = stk.NextToken(); try { cb0x = (System.Int32.Parse(str)); } catch (System.FormatException) { throw new System.ArgumentException("Bad first parameter for the " + "'-Wcboff' option: " + str); } if (cb0x < 0 || cb0x > 1) { throw new System.ArgumentException("Invalid horizontal " + "code-block partition origin."); } int cb0y = 0; str = stk.NextToken(); try { cb0y = (System.Int32.Parse(str)); } catch (System.FormatException) { throw new System.ArgumentException("Bad second parameter for the " + "'-Wcboff' option: " + str); } if (cb0y < 0 || cb0y > 1) { throw new System.ArgumentException("Invalid vertical " + "code-block partition origin."); } if (cb0x != 0 || cb0y != 0) { FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Code-blocks partition origin is " + "different from (0,0). This is defined in JPEG 2000" + " part 2 and may be not supported by all JPEG 2000 " + "decoders."); } return new ForwWTFull(src, encSpec, cb0x, cb0y); }
/// <summary> Factory method for creating instances of this class.</summary> /// <param name="src">-- source of image data /// </param> /// <param name="csMap">-- provides colorspace info /// </param> /// <returns> Resampler instance /// </returns> public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) { return new Resampler(src, csMap); }
/// <summary> Ctor which creates an ICCProfile for the image and initializes /// all data objects (input, working, and output). /// /// </summary> /// <param name="src">-- Source of image data /// </param> /// <param name="csm">-- provides colorspace info /// </param> protected internal ChannelDefinitionMapper(BlkImgDataSrc src, ColorSpace csMap) : base(src, csMap) { /* end ChannelDefinitionMapper ctor */ }
/// <summary> Ctor which creates an ICCProfile for the image and initializes /// all data objects (input, working, and output). /// /// </summary> /// <param name="src">-- Source of image data /// </param> /// <param name="csm">-- provides colorspace info /// </param> protected internal PalettizedColorSpaceMapper(BlkImgDataSrc src, ColorSpace csMap):base(src, csMap) { pbox = csMap.PaletteBox; initialize(); }
/// <summary> Factory method for creating instances of this class.</summary> /// <param name="src">-- source of image data /// </param> /// <param name="csMap">-- provides colorspace info /// </param> /// <returns> PalettizedColorSpaceMapper instance /// </returns> public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) { return(new PalettizedColorSpaceMapper(src, csMap)); }
/// <summary> Constructs a new ImgDataConverter object that operates on the specified /// source of image data. /// /// </summary> /// <param name="imgSrc">The source from where to get the data to be transformed /// /// </param> /// <seealso cref="BlkImgDataSrc"> /// /// </seealso> public ImgDataConverter(BlkImgDataSrc imgSrc) : base(imgSrc) { src = imgSrc; fp = 0; }
/// <summary> Factory method for creating instances of this class.</summary> /// <param name="src">-- source of image data /// </param> /// <param name="csMap">-- provides colorspace info /// </param> /// <returns> ColorSpaceMapper instance /// </returns> /// <exception cref="IOException">profile access exception /// </exception> public static BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) { // Check parameters csMap.pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo)); // Perform ICCProfiling or ColorSpace tranfsormation. if (csMap.Method == ColorSpace.MethodEnum.ICC_PROFILED) { return ICCProfiler.createInstance(src, csMap); } else { ColorSpace.CSEnum colorspace = csMap.getColorSpace(); if (colorspace == ColorSpace.CSEnum.sRGB) { return EnumeratedColorSpaceMapper.createInstance(src, csMap); } else if (colorspace == ColorSpace.CSEnum.GreyScale) { return EnumeratedColorSpaceMapper.createInstance(src, csMap); } else if (colorspace == ColorSpace.CSEnum.sYCC) { return SYccColorSpaceMapper.createInstance(src, csMap); } if (colorspace == ColorSpace.CSEnum.esRGB) { return EsRgbColorSpaceMapper.createInstance(src, csMap); } else if (colorspace == ColorSpace.CSEnum.Unknown) { return null; } else { throw new ColorSpaceException("Bad color space specification in image"); } } }
/// <summary> Creates a new writer to the specified file, to write data from the /// specified component. /// /// <P>The size of the image that is written to the file is the size of the /// component from which to get the data, specified by b, not the size of /// the source image (they differ if there is some sub-sampling). /// /// </summary> /// <param name="fname">The name of the file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="c">The index of the component from where to get the data. /// /// </param> public ImgWriterPGM(System.String fname, BlkImgDataSrc imgSrc, int c) : this(new System.IO.FileInfo(fname), imgSrc, c) { }
/// <summary> Creates a new PrecinctSizeSpec object for the specified number of tiles /// and components and the ParameterList instance. /// /// </summary> /// <param name="nt">The number of tiles /// /// </param> /// <param name="nc">The number of components /// /// </param> /// <param name="type">the type of the specification module i.e. tile specific, /// component specific or both. /// /// </param> /// <param name="imgsrc">The image source (used to get the image size) /// /// </param> /// <param name="pl">The ParameterList instance /// /// </param> public PrecinctSizeSpec(int nt, int nc, byte type, BlkImgDataSrc imgsrc, IntegerSpec dls, ParameterList pl):base(nt, nc, type) { this.dls = dls; // The precinct sizes are stored in a 2 elements vector array, the // first element containing a vector for the precincts width for each // resolution level and the second element containing a vector for the // precincts height for each resolution level. The precincts sizes are // specified from the highest resolution level to the lowest one // (i.e. 0). If there are less elements than the number of // decomposition levels, the last element is used for all remaining // resolution levels (i.e. if the precincts sizes are specified only // for resolutions levels 5, 4 and 3, then the precincts size for // resolution levels 2, 1 and 0 will be the same as the size used for // resolution level 3). // Boolean used to know if we were previously reading a precinct's // size or if we were reading something else. bool wasReadingPrecinctSize = false; System.String param = pl.getParameter(optName); // Set precinct sizes to default i.e. 2^15 = // Markers.PRECINCT_PARTITION_DEF_SIZE System.Collections.ArrayList[] tmpv = new System.Collections.ArrayList[2]; tmpv[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx tmpv[0].Add((System.Int32) CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE); tmpv[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy tmpv[1].Add((System.Int32) CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE); setDefault(tmpv); if (param == null) { // No precinct size specified in the command line so we do not try // to parse it. return ; } // Precinct partition is used : parse arguments SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param); byte curSpecType = SPEC_DEF; // Specification type of the // current parameter bool[] tileSpec = null; // Tiles concerned by the specification bool[] compSpec = null; // Components concerned by the specification int ci, ti; //i, xIdx removed bool endOfParamList = false; System.String word = null; // current word System.Int32 w, h; System.String errMsg = null; while ((stk.HasMoreTokens() || wasReadingPrecinctSize) && !endOfParamList) { System.Collections.ArrayList[] v = new System.Collections.ArrayList[2]; // v[0] : ppx, v[1] : ppy // We do not read the next token if we were reading a precinct's // size argument as we have already read the next token into word. if (!wasReadingPrecinctSize) { word = stk.NextToken(); } wasReadingPrecinctSize = false; switch (word[0]) { case 't': // Tiles specification tileSpec = parseIdx(word, nTiles); if (curSpecType == SPEC_COMP_DEF) { curSpecType = SPEC_TILE_COMP; } else { curSpecType = SPEC_TILE_DEF; } break; case 'c': // Components specification compSpec = parseIdx(word, nComp); if (curSpecType == SPEC_TILE_DEF) { curSpecType = SPEC_TILE_COMP; } else { curSpecType = SPEC_COMP_DEF; } break; default: if (!System.Char.IsDigit(word[0])) { errMsg = "Bad construction for parameter: " + word; throw new System.ArgumentException(errMsg); } // Initialises Vector objects v[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx v[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy while (true) { // Now get the precinct dimensions try { // Get precinct width w = System.Int32.Parse(word); // Get next word in argument list try { word = stk.NextToken(); } catch (System.ArgumentOutOfRangeException) { errMsg = "'" + optName + "' option : could not " + "parse the precinct's width"; throw new System.ArgumentException(errMsg); } // Get precinct height h = System.Int32.Parse(word); if (w != (1 << MathUtil.log2(w)) || h != (1 << MathUtil.log2(h))) { errMsg = "Precinct dimensions must be powers of 2"; throw new System.ArgumentException(errMsg); } } catch (System.FormatException) { errMsg = "'" + optName + "' option : the argument '" + word + "' could not be parsed."; throw new System.ArgumentException(errMsg); } // Store packet's dimensions in Vector arrays v[0].Add(w); v[1].Add(h); // Try to get the next token if (stk.HasMoreTokens()) { word = stk.NextToken(); if (!System.Char.IsDigit(word[0])) { // The next token does not start with a digit so // it is not a precinct's size argument. We set // the wasReadingPrecinctSize booleen such that we // know that we don't have to read another token // and check for the end of the parameters list. wasReadingPrecinctSize = true; if (curSpecType == SPEC_DEF) { setDefault(v); } else if (curSpecType == SPEC_TILE_DEF) { for (ti = tileSpec.Length - 1; ti >= 0; ti--) { if (tileSpec[ti]) { setTileDef(ti, v); } } } else if (curSpecType == SPEC_COMP_DEF) { for (ci = compSpec.Length - 1; ci >= 0; ci--) { if (compSpec[ci]) { setCompDef(ci, v); } } } else { for (ti = tileSpec.Length - 1; ti >= 0; ti--) { for (ci = compSpec.Length - 1; ci >= 0; ci--) { if (tileSpec[ti] && compSpec[ci]) { setTileCompVal(ti, ci, v); } } } } // Re-initialize curSpecType = SPEC_DEF; tileSpec = null; compSpec = null; // Go back to 'normal' parsing break; } else { // Next token starts with a digit so read it } } else { // We have reached the end of the parameters list so // we store the last precinct's sizes and we stop if (curSpecType == SPEC_DEF) { setDefault(v); } else if (curSpecType == SPEC_TILE_DEF) { for (ti = tileSpec.Length - 1; ti >= 0; ti--) { if (tileSpec[ti]) { setTileDef(ti, v); } } } else if (curSpecType == SPEC_COMP_DEF) { for (ci = compSpec.Length - 1; ci >= 0; ci--) { if (compSpec[ci]) { setCompDef(ci, v); } } } else { for (ti = tileSpec.Length - 1; ti >= 0; ti--) { for (ci = compSpec.Length - 1; ci >= 0; ci--) { if (tileSpec[ti] && compSpec[ci]) { setTileCompVal(ti, ci, v); } } } } endOfParamList = true; break; } } // while (true) break; } // switch } // while }
/// <summary> Constructs a new ImgDataConverter object that operates on the specified /// source of image data. /// /// </summary> /// <param name="imgSrc">The source from where to get the data to be transformed /// /// </param> /// <seealso cref="BlkImgDataSrc"> /// /// </seealso> public ImgDataConverter(BlkImgDataSrc imgSrc):base(imgSrc) { src = imgSrc; fp = 0; }
/// <summary> Initializes this object with the given source of image data and with /// all the decompositon parameters /// /// </summary> /// <param name="src">From where the image data should be obtained. /// /// </param> /// <param name="encSpec">The encoder specifications /// /// </param> /// <param name="cb0x">The horizontal coordinate of the code-block partition /// origin on the reference grid. /// /// </param> /// <param name="cb0y">The vertical coordinate of the code-block partition origin /// on the reference grid. /// /// </param> /// <seealso cref="ForwardWT"> /// /// </seealso> public ForwWTFull(BlkImgDataSrc src, EncoderSpecs encSpec, int cb0x, int cb0y):base(src) { this.src = src; this.cb0x = cb0x; this.cb0y = cb0y; this.dls = encSpec.dls; this.filters = encSpec.wfs; this.cblks = encSpec.cblks; this.pss = encSpec.pss; int ncomp = src.NumComps; int ntiles = src.getNumTiles(); currentSubband = new SubbandAn[ncomp]; decomposedComps = new DataBlk[ncomp]; subbTrees = new SubbandAn[ntiles][]; for (int i = 0; i < ntiles; i++) { subbTrees[i] = new SubbandAn[ncomp]; } lastn = new int[ncomp]; lastm = new int[ncomp]; }
/// <summary> Creates a ForwardWT object with the specified filters, and with other /// options specified in the parameter list 'pl'. /// /// </summary> /// <param name="src">The source of data to be transformed /// /// </param> /// <param name="pl">The parameter list (or options). /// /// </param> /// <param name="kers">The encoder specifications. /// /// </param> /// <returns> A new ForwardWT object with the specified filters and options /// from 'pl'. /// /// </returns> /// <exception cref="IllegalArgumentException">If mandatory parameters are missing /// or if invalid values are given. /// /// </exception> public static ForwardWT createInstance(BlkImgDataSrc src, ParameterList pl, EncoderSpecs encSpec) { int deflev; // defdec removed //System.String decompstr; //System.String wtstr; //System.String pstr; //SupportClass.StreamTokenizerSupport stok; //SupportClass.Tokenizer strtok; //int prefx, prefy; // Partitioning reference point coordinates // Check parameters pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo)); deflev = ((System.Int32)encSpec.dls.getDefault()); // Code-block partition origin System.String str = ""; if (pl.getParameter("Wcboff") == null) { throw new System.InvalidOperationException("You must specify an argument to the '-Wcboff' " + "option. See usage with the '-u' option"); } SupportClass.Tokenizer stk = new SupportClass.Tokenizer(pl.getParameter("Wcboff")); if (stk.Count != 2) { throw new System.ArgumentException("'-Wcboff' option needs two" + " arguments. See usage with " + "the '-u' option."); } int cb0x = 0; str = stk.NextToken(); try { cb0x = (System.Int32.Parse(str)); } catch (System.FormatException e) { throw new System.ArgumentException("Bad first parameter for the " + "'-Wcboff' option: " + str); } if (cb0x < 0 || cb0x > 1) { throw new System.ArgumentException("Invalid horizontal " + "code-block partition origin."); } int cb0y = 0; str = stk.NextToken(); try { cb0y = (System.Int32.Parse(str)); } catch (System.FormatException e) { throw new System.ArgumentException("Bad second parameter for the " + "'-Wcboff' option: " + str); } if (cb0y < 0 || cb0y > 1) { throw new System.ArgumentException("Invalid vertical " + "code-block partition origin."); } if (cb0x != 0 || cb0y != 0) { FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Code-blocks partition origin is " + "different from (0,0). This is defined in JPEG 2000" + " part 2 and may be not supported by all JPEG 2000 " + "decoders."); } return(new ForwWTFull(src, encSpec, cb0x, cb0y)); }
/// <summary> Constructs a new ForwCompTransf object that operates on the /// specified source of image data. /// /// </summary> /// <param name="imgSrc">The source from where to get the data to be /// transformed /// /// </param> /// <param name="decSpec">The decoder specifications /// /// </param> /// <param name="utdepth">The bit depth of the un-transformed components /// /// </param> /// <param name="pl">The command line optinons of the decoder /// /// </param> /// <seealso cref="BlkImgDataSrc"> /// /// </seealso> public InvCompTransf(BlkImgDataSrc imgSrc, DecoderSpecs decSpec, int[] utdepth, ParameterList pl):base(imgSrc) { this.cts = decSpec.cts; this.wfs = decSpec.wfs; src = imgSrc; this.utdepth = utdepth; noCompTransf = !(pl.getBooleanParameter("comp_transf")); }
/// <summary> Constructs a new ImgDataConverter object that operates on the specified /// source of image data. /// /// </summary> /// <param name="imgSrc">The source from where to get the data to be transformed /// /// </param> /// <param name="fp">The number of fraction bits in the casted ints /// /// </param> /// <seealso cref="BlkImgDataSrc"> /// /// </seealso> public ImgDataConverter(BlkImgDataSrc imgSrc, int fp):base(imgSrc) { src = imgSrc; this.fp = fp; }
/// <summary> Creates a new writer to the specified File object, to write data from /// the specified component. /// /// <p>The three components that will be written as R, G and B must be /// specified through the b1, b2 and b3 arguments.</p> /// /// </summary> /// <param name="out">The file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="n1">The index of the first component from where to get the data, /// that will be written as the red channel. /// /// </param> /// <param name="n2">The index of the second component from where to get the data, /// that will be written as the green channel. /// /// </param> /// <param name="n3">The index of the third component from where to get the data, /// that will be written as the green channel. /// /// </param> /// <seealso cref="DataBlk"> /// /// </seealso> public ImgWriterPPM(IFileInfo out_Renamed, BlkImgDataSrc imgSrc, int n1, int n2, int n3) { // Check that imgSrc is of the correct type // Check that the component index is valid if ((n1 < 0) || (n1 >= imgSrc.NumComps) || (n2 < 0) || (n2 >= imgSrc.NumComps) || (n3 < 0) || (n3 >= imgSrc.NumComps) || (imgSrc.getNomRangeBits(n1) > 8) || (imgSrc.getNomRangeBits(n2) > 8) || (imgSrc.getNomRangeBits(n3) > 8)) { throw new System.ArgumentException("Invalid component indexes"); } // Initialize w = imgSrc.getCompImgWidth(n1); h = imgSrc.getCompImgHeight(n1); // Check that all components have same width and height if (w != imgSrc.getCompImgWidth(n2) || w != imgSrc.getCompImgWidth(n3) || h != imgSrc.getCompImgHeight(n2) || h != imgSrc.getCompImgHeight(n3)) { throw new System.ArgumentException("All components must have the" + " same dimensions and no" + " subsampling"); } w = imgSrc.ImgWidth; h = imgSrc.ImgHeight; // Continue initialization if (out_Renamed.Exists && !out_Renamed.Delete()) { throw new System.IO.IOException("Could not reset file"); } this.out_Renamed = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(out_Renamed, "rw"); src = imgSrc; cps[0] = n1; cps[1] = n2; cps[2] = n3; fb[0] = imgSrc.getFixedPoint(n1); fb[1] = imgSrc.getFixedPoint(n2); fb[2] = imgSrc.getFixedPoint(n3); levShift[0] = 1 << (imgSrc.getNomRangeBits(n1) - 1); levShift[1] = 1 << (imgSrc.getNomRangeBits(n2) - 1); levShift[2] = 1 << (imgSrc.getNomRangeBits(n3) - 1); writeHeaderInfo(); }
/// <summary> Creates a new writer to the specified File object, to write data from /// the specified component. /// /// <p>The size of the image that is written to the file is the size of the /// component from which to get the data, specified by b, not the size of /// the source image (they differ if there is some sub-sampling).</p> /// /// <p>All the header informations are given by the BlkImgDataSrc source /// (component width, component height, bit-depth) and sign flag, which are /// provided to the constructor. The endianness is always big-endian (MSB /// first).</p> /// /// </summary> /// <param name="out">The file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="c">The index of the component from where to get the data. /// /// </param> /// <param name="isSigned">Whether the datas are signed or not (needed only when /// writing header). /// /// </param> /// <seealso cref="DataBlk"> /// /// </seealso> public ImgWriterPGX(System.IO.FileInfo out_Renamed, BlkImgDataSrc imgSrc, int c, bool isSigned) { //Initialize this.c = c; bool tmpBool; if (System.IO.File.Exists(out_Renamed.FullName)) tmpBool = true; else tmpBool = System.IO.Directory.Exists(out_Renamed.FullName); bool tmpBool2; if (System.IO.File.Exists(out_Renamed.FullName)) { System.IO.File.Delete(out_Renamed.FullName); tmpBool2 = true; } else if (System.IO.Directory.Exists(out_Renamed.FullName)) { System.IO.Directory.Delete(out_Renamed.FullName); tmpBool2 = true; } else tmpBool2 = false; if (tmpBool && !tmpBool2) { throw new System.IO.IOException("Could not reset file"); } this.out_Renamed = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(out_Renamed, "rw"); this.isSigned = isSigned; src = imgSrc; w = src.ImgWidth; h = src.ImgHeight; fb = imgSrc.getFixedPoint(c); bitDepth = src.getNomRangeBits(this.c); if ((bitDepth <= 0) || (bitDepth > 31)) { throw new System.IO.IOException("PGX supports only bit-depth between " + "1 and 31"); } if (bitDepth <= 8) { packBytes = 1; } else if (bitDepth <= 16) { packBytes = 2; } else { // <= 31 packBytes = 4; } // Writes PGX header System.String tmpString = "PG " + "ML " + ((this.isSigned)?"- ":"+ ") + bitDepth + " " + w + " " + h + "\n"; // component height byte[] tmpByte = System.Text.ASCIIEncoding.ASCII.GetBytes(tmpString); for (int i = 0; i < tmpByte.Length; i++) { this.out_Renamed.WriteByte((byte) tmpByte[i]); } offset = tmpByte.Length; maxVal = this.isSigned?((1 << (src.getNomRangeBits(c) - 1)) - 1):((1 << src.getNomRangeBits(c)) - 1); minVal = this.isSigned?((- 1) * (1 << (src.getNomRangeBits(c) - 1))):0; levShift = (this.isSigned)?0:1 << (src.getNomRangeBits(c) - 1); }
public static Image FromStream(Stream stream) { RandomAccessIO in_stream = new ISRandomAccessIO(stream); // Initialize default parameters ParameterList defpl = GetDefaultParameterList(decoder_pinfo); // Create parameter list using defaults ParameterList pl = new ParameterList(defpl); // **** File Format **** // If the codestream is wrapped in the jp2 fileformat, Read the // file format wrapper FileFormatReader ff = new FileFormatReader(in_stream); ff.readFileFormat(); if (ff.JP2FFUsed) { in_stream.seek(ff.FirstCodeStreamPos); } // +----------------------------+ // | Instantiate decoding chain | // +----------------------------+ // **** Header decoder **** // Instantiate header decoder and read main header HeaderInfo hi = new HeaderInfo(); HeaderDecoder hd; try { hd = new HeaderDecoder(in_stream, pl, hi); } catch (EndOfStreamException e) { throw new ApplicationException("Codestream too short or bad header, unable to decode.", e); } int nCompCod = hd.NumComps; int nTiles = hi.sizValue.NumTiles; DecoderSpecs decSpec = hd.DecoderSpecs; // Get demixed bitdepths int[] depth = new int[nCompCod]; for (int i = 0; i < nCompCod; i++) { depth[i] = hd.getOriginalBitDepth(i); } // **** Bit stream reader **** BitstreamReaderAgent breader; try { breader = BitstreamReaderAgent. createInstance(in_stream, hd, pl, decSpec, false, hi); } catch (IOException e) { throw new ApplicationException("Error while reading bit stream header or parsing packets.", e); } catch (ArgumentException e) { throw new ApplicationException("Cannot instantiate bit stream reader.", e); } // **** Entropy decoder **** EntropyDecoder entdec; try { entdec = hd.createEntropyDecoder(breader, pl); } catch (ArgumentException e) { throw new ApplicationException("Cannot instantiate entropy decoder.", e); } // **** ROI de-scaler **** ROIDeScaler roids; try { roids = hd.createROIDeScaler(entdec, pl, decSpec); } catch (ArgumentException e) { throw new ApplicationException("Cannot instantiate roi de-scaler.", e); } // **** Dequantizer **** Dequantizer deq; try { deq = hd.createDequantizer(roids, depth, decSpec); } catch (ArgumentException e) { throw new ApplicationException("Cannot instantiate dequantizer.", e); } // **** Inverse wavelet transform *** InverseWT invWT; try { // full page inverse wavelet transform invWT = InverseWT.createInstance(deq, decSpec); } catch (ArgumentException e) { throw new ApplicationException("Cannot instantiate inverse wavelet transform.", e); } int res = breader.ImgRes; invWT.ImgResLevel = res; // **** Data converter **** (after inverse transform module) ImgDataConverter converter = new ImgDataConverter(invWT, 0); // **** Inverse component transformation **** InvCompTransf ictransf = new InvCompTransf(converter, decSpec, depth, pl); // **** Color space mapping **** BlkImgDataSrc color; if (ff.JP2FFUsed && pl.getParameter("nocolorspace").Equals("off")) { try { ColorSpace csMap = new ColorSpace(in_stream, hd, pl); BlkImgDataSrc channels = hd.createChannelDefinitionMapper(ictransf, csMap); BlkImgDataSrc resampled = hd.createResampler(channels, csMap); BlkImgDataSrc palettized = hd.createPalettizedColorSpaceMapper(resampled, csMap); color = hd.createColorSpaceMapper(palettized, csMap); } catch (ArgumentException e) { throw new ApplicationException("Could not instantiate ICC profiler.", e); } catch (ColorSpaceException e) { throw new ApplicationException("Error processing ColorSpace information.", e); } } else { // Skip colorspace mapping color = ictransf; } // This is the last image in the decoding chain and should be // assigned by the last transformation: BlkImgDataSrc decodedImage = color; if (color == null) { decodedImage = ictransf; } int numComps = decodedImage.NumComps; int bytesPerPixel = numComps; // Assuming 8-bit components // **** Copy to Bitmap **** PixelFormat pixelFormat; switch (numComps) { case 1: pixelFormat = PixelFormat.Format24bppRgb; break; case 3: pixelFormat = PixelFormat.Format24bppRgb; break; case 4: case 5: pixelFormat = PixelFormat.Format32bppArgb; break; default: throw new ApplicationException("Unsupported PixelFormat. " + numComps + " components."); } Bitmap dst = new Bitmap(decodedImage.ImgWidth, decodedImage.ImgHeight, pixelFormat); Coord numTiles = decodedImage.getNumTiles(null); int tIdx = 0; for (int y = 0; y < numTiles.y; y++) { // Loop on horizontal tiles for (int x = 0; x < numTiles.x; x++, tIdx++) { decodedImage.setTile(x, y); int height = decodedImage.getTileCompHeight(tIdx, 0); int width = decodedImage.getTileCompWidth(tIdx, 0); int tOffx = decodedImage.getCompULX(0) - (int)Math.Ceiling(decodedImage.ImgULX / (double)decodedImage.getCompSubsX(0)); int tOffy = decodedImage.getCompULY(0) - (int)Math.Ceiling(decodedImage.ImgULY / (double)decodedImage.getCompSubsY(0)); DataBlkInt[] db = new DataBlkInt[numComps]; int[] ls = new int[numComps]; int[] mv = new int[numComps]; int[] fb = new int[numComps]; for (int i = 0; i < numComps; i++) { db[i] = new DataBlkInt(); ls[i] = 1 << (decodedImage.getNomRangeBits(0) - 1); mv[i] = (1 << decodedImage.getNomRangeBits(0)) - 1; fb[i] = decodedImage.getFixedPoint(0); } for (int l = 0; l < height; l++) { for (int i = numComps - 1; i >= 0; i--) { db[i].ulx = 0; db[i].uly = l; db[i].w = width; db[i].h = 1; decodedImage.getInternCompData(db[i], i); } int[] k = new int[numComps]; for (int i = numComps - 1; i >= 0; i--) { k[i] = db[i].offset + width - 1; } int outputBytesPerPixel = Math.Max(3, Math.Min(4, bytesPerPixel)); byte[] rowvalues = new byte[width * outputBytesPerPixel]; for (int i = width - 1; i >= 0; i--) { int[] tmp = new int[numComps]; for (int j = numComps - 1; j >= 0; j--) { tmp[j] = (db[j].data_array[k[j]--] >> fb[j]) + ls[j]; tmp[j] = (tmp[j] < 0) ? 0 : ((tmp[j] > mv[j]) ? mv[j] : tmp[j]); if (decodedImage.getNomRangeBits(j) != 8) { tmp[j] = (int)Math.Round(((double)tmp[j] / Math.Pow(2D, (double)decodedImage.getNomRangeBits(j))) * 255D); } } int offset = i * outputBytesPerPixel; switch (numComps) { case 1: rowvalues[offset + 0] = (byte)tmp[0]; rowvalues[offset + 1] = (byte)tmp[0]; rowvalues[offset + 2] = (byte)tmp[0]; break; case 3: rowvalues[offset + 0] = (byte)tmp[2]; rowvalues[offset + 1] = (byte)tmp[1]; rowvalues[offset + 2] = (byte)tmp[0]; break; case 4: case 5: rowvalues[offset + 0] = (byte)tmp[2]; rowvalues[offset + 1] = (byte)tmp[1]; rowvalues[offset + 2] = (byte)tmp[0]; rowvalues[offset + 3] = (byte)tmp[3]; break; } } BitmapData dstdata = dst.LockBits( new System.Drawing.Rectangle(tOffx, tOffy + l, width, 1), ImageLockMode.WriteOnly, pixelFormat); IntPtr ptr = dstdata.Scan0; System.Runtime.InteropServices.Marshal.Copy(rowvalues, 0, ptr, rowvalues.Length); dst.UnlockBits(dstdata); } } } return(dst); }
/// <summary> Creates a new PrecinctSizeSpec object for the specified number of tiles /// and components and the ParameterList instance. /// /// </summary> /// <param name="nt">The number of tiles /// /// </param> /// <param name="nc">The number of components /// /// </param> /// <param name="type">the type of the specification module i.e. tile specific, /// component specific or both. /// /// </param> /// <param name="imgsrc">The image source (used to get the image size) /// /// </param> /// <param name="pl">The ParameterList instance /// /// </param> public PrecinctSizeSpec(int nt, int nc, byte type, BlkImgDataSrc imgsrc, IntegerSpec dls, ParameterList pl) : base(nt, nc, type) { this.dls = dls; // The precinct sizes are stored in a 2 elements vector array, the // first element containing a vector for the precincts width for each // resolution level and the second element containing a vector for the // precincts height for each resolution level. The precincts sizes are // specified from the highest resolution level to the lowest one // (i.e. 0). If there are less elements than the number of // decomposition levels, the last element is used for all remaining // resolution levels (i.e. if the precincts sizes are specified only // for resolutions levels 5, 4 and 3, then the precincts size for // resolution levels 2, 1 and 0 will be the same as the size used for // resolution level 3). // Boolean used to know if we were previously reading a precinct's // size or if we were reading something else. bool wasReadingPrecinctSize = false; System.String param = pl.getParameter(optName); // Set precinct sizes to default i.e. 2^15 = // Markers.PRECINCT_PARTITION_DEF_SIZE System.Collections.ArrayList[] tmpv = new System.Collections.ArrayList[2]; tmpv[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx tmpv[0].Add((System.Int32)CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE); tmpv[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy tmpv[1].Add((System.Int32)CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE); setDefault(tmpv); if (param == null) { // No precinct size specified in the command line so we do not try // to parse it. return; } // Precinct partition is used : parse arguments SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param); byte curSpecType = SPEC_DEF; // Specification type of the // current parameter bool[] tileSpec = null; // Tiles concerned by the specification bool[] compSpec = null; // Components concerned by the specification int ci, ti; //i, xIdx removed bool endOfParamList = false; System.String word = null; // current word System.Int32 w, h; System.String errMsg = null; while ((stk.HasMoreTokens() || wasReadingPrecinctSize) && !endOfParamList) { System.Collections.ArrayList[] v = new System.Collections.ArrayList[2]; // v[0] : ppx, v[1] : ppy // We do not read the next token if we were reading a precinct's // size argument as we have already read the next token into word. if (!wasReadingPrecinctSize) { word = stk.NextToken(); } wasReadingPrecinctSize = false; switch (word[0]) { case 't': // Tiles specification tileSpec = parseIdx(word, nTiles); if (curSpecType == SPEC_COMP_DEF) { curSpecType = SPEC_TILE_COMP; } else { curSpecType = SPEC_TILE_DEF; } break; case 'c': // Components specification compSpec = parseIdx(word, nComp); if (curSpecType == SPEC_TILE_DEF) { curSpecType = SPEC_TILE_COMP; } else { curSpecType = SPEC_COMP_DEF; } break; default: if (!System.Char.IsDigit(word[0])) { errMsg = "Bad construction for parameter: " + word; throw new System.ArgumentException(errMsg); } // Initialises Vector objects v[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx v[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy while (true) { // Now get the precinct dimensions try { // Get precinct width w = System.Int32.Parse(word); // Get next word in argument list try { word = stk.NextToken(); } catch (System.ArgumentOutOfRangeException) { errMsg = "'" + optName + "' option : could not " + "parse the precinct's width"; throw new System.ArgumentException(errMsg); } // Get precinct height h = System.Int32.Parse(word); if (w != (1 << MathUtil.log2(w)) || h != (1 << MathUtil.log2(h))) { errMsg = "Precinct dimensions must be powers of 2"; throw new System.ArgumentException(errMsg); } } catch (System.FormatException) { errMsg = "'" + optName + "' option : the argument '" + word + "' could not be parsed."; throw new System.ArgumentException(errMsg); } // Store packet's dimensions in Vector arrays v[0].Add(w); v[1].Add(h); // Try to get the next token if (stk.HasMoreTokens()) { word = stk.NextToken(); if (!System.Char.IsDigit(word[0])) { // The next token does not start with a digit so // it is not a precinct's size argument. We set // the wasReadingPrecinctSize booleen such that we // know that we don't have to read another token // and check for the end of the parameters list. wasReadingPrecinctSize = true; if (curSpecType == SPEC_DEF) { setDefault(v); } else if (curSpecType == SPEC_TILE_DEF) { for (ti = tileSpec.Length - 1; ti >= 0; ti--) { if (tileSpec[ti]) { setTileDef(ti, v); } } } else if (curSpecType == SPEC_COMP_DEF) { for (ci = compSpec.Length - 1; ci >= 0; ci--) { if (compSpec[ci]) { setCompDef(ci, v); } } } else { for (ti = tileSpec.Length - 1; ti >= 0; ti--) { for (ci = compSpec.Length - 1; ci >= 0; ci--) { if (tileSpec[ti] && compSpec[ci]) { setTileCompVal(ti, ci, v); } } } } // Re-initialize curSpecType = SPEC_DEF; tileSpec = null; compSpec = null; // Go back to 'normal' parsing break; } else { // Next token starts with a digit so read it } } else { // We have reached the end of the parameters list so // we store the last precinct's sizes and we stop if (curSpecType == SPEC_DEF) { setDefault(v); } else if (curSpecType == SPEC_TILE_DEF) { for (ti = tileSpec.Length - 1; ti >= 0; ti--) { if (tileSpec[ti]) { setTileDef(ti, v); } } } else if (curSpecType == SPEC_COMP_DEF) { for (ci = compSpec.Length - 1; ci >= 0; ci--) { if (compSpec[ci]) { setCompDef(ci, v); } } } else { for (ti = tileSpec.Length - 1; ti >= 0; ti--) { for (ci = compSpec.Length - 1; ci >= 0; ci--) { if (tileSpec[ti] && compSpec[ci]) { setTileCompVal(ti, ci, v); } } } } endOfParamList = true; break; } } // while (true) break; } // switch } // while }
/// <summary> Creates a new writer to the specified file, to write data from the /// specified component. /// /// <p>The three components that will be written as R, G and B must be /// specified through the b1, b2 and b3 arguments.</p> /// /// </summary> /// <param name="fname">The name of the file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="n1">The index of the first component from where to get the data, /// that will be written as the red channel. /// /// </param> /// <param name="n2">The index of the second component from where to get the data, /// that will be written as the green channel. /// /// </param> /// <param name="n3">The index of the third component from where to get the data, /// that will be written as the green channel. /// /// </param> /// <seealso cref="DataBlk"> /// /// </seealso> public ImgWriterPPM(System.String fname, BlkImgDataSrc imgSrc, int n1, int n2, int n3) : this(FileInfoFactory.New(fname), imgSrc, n1, n2, n3) { }
/// <summary> Creates a new writer to the specified file, to write data from the /// specified component. /// /// <p>The size of the image that is written to the file is the size of the /// component from which to get the data, specified by b, not the size of /// the source image (they differ if there is some sub-sampling).</p> /// /// <p>All header information is given by the BlkImgDataSrc source /// (component width, component height, bit-depth) and sign flag, which are /// provided to the constructor. The endianness is always big-endian (MSB /// first). /// /// </summary> /// <param name="fname">The name of the file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="c">The index of the component from where to get the data. /// /// </param> /// <param name="isSigned">Whether the datas are signed or not (needed only when /// writing header). /// /// </param> /// <seealso cref="DataBlk"> /// /// </seealso> public ImgWriterPGX(System.String fname, BlkImgDataSrc imgSrc, int c, bool isSigned) : this(new System.IO.FileInfo(fname), imgSrc, c, isSigned) { }
/// <summary> Initialize all members with the given number of tiles and components /// and the command-line arguments stored in a ParameterList instance /// /// </summary> /// <param name="nt">Number of tiles /// /// </param> /// <param name="nc">Number of components /// /// </param> /// <param name="imgsrc">The image source (used to get the image size) /// /// </param> /// <param name="pl">The ParameterList instance /// /// </param> public EncoderSpecs(int nt, int nc, BlkImgDataSrc imgsrc, ParameterList pl) { nTiles = nt; nComp = nc; // ROI rois = new MaxShiftSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP); // Quantization pl.checkList(Quantizer.OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(Quantizer.ParameterInfo)); qts = new QuantTypeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl); qsss = new QuantStepSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl); gbs = new GuardBitsSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl); // Wavelet transform wfs = new AnWTFilterSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, qts, pl); dls = new IntegerSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl, "Wlev"); // Component transformation cts = new ForwCompTransfSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE, wfs, pl); // Entropy coder System.String[] strLcs = new System.String[]{"near_opt", "lazy_good", "lazy"}; lcs = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Clen_calc", strLcs, pl); System.String[] strTerm = new System.String[]{"near_opt", "easy", "predict", "full"}; tts = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cterm_type", strTerm, pl); System.String[] strBoolean = new System.String[]{"on", "off"}; sss = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cseg_symbol", strBoolean, pl); css = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Ccausal", strBoolean, pl); rts = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cterminate", strBoolean, pl); mqrs = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "CresetMQ", strBoolean, pl); bms = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cbypass", strBoolean, pl); cblks = new CBlkSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl); // Precinct partition pss = new PrecinctSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, imgsrc, dls, pl); // Codestream sops = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE, "Psop", strBoolean, pl); ephs = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE, "Peph", strBoolean, pl); }
/// <summary> Creates a new writer to the specified file, to write data from the /// specified component. /// /// <p>The three components that will be written as R, G and B must be /// specified through the b1, b2 and b3 arguments.</p> /// /// </summary> /// <param name="fname">The name of the file where to write the data /// /// </param> /// <param name="imgSrc">The source from where to get the image data to write. /// /// </param> /// <param name="n1">The index of the first component from where to get the data, /// that will be written as the red channel. /// /// </param> /// <param name="n2">The index of the second component from where to get the data, /// that will be written as the green channel. /// /// </param> /// <param name="n3">The index of the third component from where to get the data, /// that will be written as the green channel. /// /// </param> /// <seealso cref="DataBlk"> /// /// </seealso> public ImgWriterPPM(System.String fname, BlkImgDataSrc imgSrc, int n1, int n2, int n3) : this(FileInfoFactory.New(fname), imgSrc, n1, n2, n3) { }
/// <summary> Creates and returns the Resampler which converts the input /// source to one in which all channels have the same number of /// samples. This is required for colorspace conversions. /// /// </summary> /// <param name="src">The bit stream reader agent where to get code-block /// data from. /// </param> /// <param name="csMap">provides color space information from the image file /// /// </param> /// <returns> The resampled BlkImgDataSrc /// </returns> /// <exception cref="IOException">image access exception /// </exception> /// <exception cref="ColorSpaceException">if image contains a bad colorspace box /// /// </exception> public virtual BlkImgDataSrc createResampler(BlkImgDataSrc src, CSJ2K.Color.ColorSpace csMap) { return Resampler.createInstance(src, csMap); }
/// <summary> Factory method for creating instances of this class.</summary> /// <param name="src">-- source of image data /// </param> /// <param name="csMap">-- provides colorspace info /// </param> /// <returns> ICCProfiler instance /// </returns> /// <exception cref="IOException">profile access exception /// </exception> /// <exception cref="ICCProfileException">profile content exception /// </exception> public static new BlkImgDataSrc createInstance(BlkImgDataSrc src, CSJ2K.Color.ColorSpace csMap) { return new ICCProfiler(src, csMap); }
/// <summary> Ctor which creates an ICCProfile for the image and initializes /// all data objects (input, working, output). /// /// </summary> /// <param name="src">-- Source of image data /// </param> /// <param name="csm">-- provides colorspace info /// /// </param> /// <exception cref="IOException"> /// </exception> /// <exception cref="ICCProfileException"> /// </exception> /// <exception cref="IllegalArgumentException"> /// </exception> protected internal ICCProfiler(BlkImgDataSrc src, CSJ2K.Color.ColorSpace csMap):base(src, csMap) { initialize(); iccp = getICCProfile(csMap); if (ncomps == 1) { xform = new MonochromeTransformTosRGB(iccp, maxValueArray[0], shiftValueArray[0]); } else { xform = new MatrixBasedTransformTosRGB(iccp, maxValueArray, shiftValueArray); } /* end ICCProfiler ctor */ }
/// <summary> Creates and returns the ChannelDefinitonMapper which maps the /// input channels to the channel definition for the appropriate /// colorspace. /// /// </summary> /// <param name="src">The bit stream reader agent where to get code-block /// data from. /// </param> /// <param name="csMap">provides color space information from the image file /// /// </param> /// <returns> The channel definition mapping object /// </returns> /// <exception cref="IOException">image access exception /// </exception> /// <exception cref="ColorSpaceException">if image contains a bad colorspace box /// /// </exception> public virtual BlkImgDataSrc createChannelDefinitionMapper(BlkImgDataSrc src, CSJ2K.Color.ColorSpace csMap) { return ChannelDefinitionMapper.createInstance(src, csMap); }
/// <summary> Creates and returns the PalettizedColorSpaceMapper which uses /// the input samples as indicies into a sample palette to /// construct the output. /// /// </summary> /// <param name="src">The bit stream reader agent where to get code-block /// data from. /// </param> /// <param name="csMap">provides color space information from the image file /// /// </param> /// <returns> a PalettizedColorSpaceMapper instance /// </returns> /// <exception cref="IOException">image access exception /// </exception> /// <exception cref="ColorSpaceException">if image contains a bad colorspace box /// /// </exception> public virtual BlkImgDataSrc createPalettizedColorSpaceMapper(BlkImgDataSrc src, CSJ2K.Color.ColorSpace csMap) { return PalettizedColorSpaceMapper.createInstance(src, csMap); }