Beispiel #1
0
void PLTFile::getColorRows(byte rows[4 * 256 * kLayerMAX], const uint8 colors[kLayerMAX]) {
	for (uint i = 0; i < kLayerMAX; i++, rows += 4 * 256) {
		ImageDecoder *palette = 0;

		try {
			palette = getLayerPalette(i, colors[i]);

			// The images have their origin at the bottom left, so we flip the color row
			const uint8 row = palette->getMipMap(0).height - 1 - colors[i];

			// Copy the whole row into the buffer
			memcpy(rows, palette->getMipMap(0).data + (row * 4 * 256), 4 * 256);

		} catch (Common::Exception &e) {
			// On error set to pink (while honoring intensity), for high debug visibility
			for (uint32 p = 0; p < 256; p++) {
				rows[p * 4 + 0] = p;
				rows[p * 4 + 1] = 0x00;
				rows[p * 4 + 2] = p;
				rows[p * 4 + 3] = 0xFF;
			}

			e.add("Failed to load palette \"%s\"", kPalettes[i]);
			Common::printException(e, "WARNING: ");
		}

		delete palette;
	}
}
Beispiel #2
0
/** Load a specific layer palette image and perform some sanity checks. */
ImageDecoder *PLTFile::getLayerPalette(uint32 layer, uint8 row) {
	assert(layer < kLayerMAX);

	// TODO: We may want to cache these somehow...
	ImageDecoder *palette = loadImage(kPalettes[layer]);
	try {
		if (palette->getFormat() != kPixelFormatBGRA)
			throw Common::Exception("Invalid format (%d)", palette->getFormat());

		if (palette->getMipMapCount() < 1)
			throw Common::Exception("No mip maps");

		const ImageDecoder::MipMap &mipMap = palette->getMipMap(0);

		if (mipMap.width != 256)
			throw Common::Exception("Invalid width (%d)", mipMap.width);

		if (row >= mipMap.height)
			throw Common::Exception("Invalid height (%d >= %d)", row, mipMap.height);

	} catch (...) {
		delete palette;
		throw;
	}

	return palette;
}
Beispiel #3
0
Surface *ImageDecoder::loadFile(Common::SeekableReadStream &stream, const PixelFormat &format) {
	// TODO: implement support for bzipped memory

	// FIXME: this is not a very nice solution but it should work
	// for the moment, we should use a different way to get all
	// decoders
	static BMPDecoder bmpDecoder;
	static ImageDecoder *decoderList[] = {
		&bmpDecoder,			// for uncompressed .BMP files
		0
	};

	ImageDecoder *decoder = 0;
	for (int i = 0; decoderList[i] != 0; ++i) {
		if (decoderList[i]->decodeable(stream)) {
			decoder = decoderList[i];
			break;
		}
	}

	if (!decoder)
		return 0;

	return decoder->decodeImage(stream, format);
}
void _SYS_image_BG1DrawRect(struct _SYSAttachedVideoBuffer *vbuf,
    const _SYSAssetImage *im, struct _SYSInt2 *destXY, unsigned frame,
        struct _SYSInt2 *srcXY, struct _SYSInt2 *size)
{
    if (!isAligned(vbuf) || !isAligned(im) ||
        !isAligned(destXY) || !isAligned(srcXY) || !isAligned(size))
        return SvmRuntime::fault(F_SYSCALL_ADDR_ALIGN);

    if (!SvmMemory::mapRAM(vbuf))
        return SvmRuntime::fault(F_SYSCALL_ADDRESS);

    struct _SYSInt2 lDestXY, lSrcXY, lSize;
    if (!SvmMemory::copyROData(lDestXY, destXY))
        return SvmRuntime::fault(F_SYSCALL_ADDRESS);
    if (!SvmMemory::copyROData(lSrcXY, srcXY))
        return SvmRuntime::fault(F_SYSCALL_ADDRESS);
    if (!SvmMemory::copyROData(lSize, size))
        return SvmRuntime::fault(F_SYSCALL_ADDRESS);

    ImageDecoder decoder;
    if (!decoder.init(im, vbuf->cube))
        return SvmRuntime::fault(F_BAD_ASSET_IMAGE);

    ImageIter iter(decoder, frame, lSrcXY.x, lSrcXY.y, lSize.x, lSize.y);
    iter.copyToBG1(vbuf->vbuf, lDestXY.x, lDestXY.y);
}
void _SYS_image_memDrawRect(uint16_t *dest, _SYSCubeID destCID,
    const _SYSAssetImage *im, unsigned dest_stride, unsigned frame,
    struct _SYSInt2 *srcXY, struct _SYSInt2 *size)
{
    if (!isAligned(dest, 2) || !isAligned(im) || !isAligned(srcXY) || !isAligned(size))
        return SvmRuntime::fault(F_SYSCALL_ADDR_ALIGN);

    struct _SYSInt2 lSrcXY, lSize;
    if (!SvmMemory::copyROData(lSrcXY, srcXY))
        return SvmRuntime::fault(F_SYSCALL_ADDRESS);
    if (!SvmMemory::copyROData(lSize, size))
        return SvmRuntime::fault(F_SYSCALL_ADDRESS);

    ImageDecoder decoder;
    if (destCID == _SYS_CUBE_ID_INVALID) {
        // Relocation disabled
        if (!decoder.init(im))
            return SvmRuntime::fault(F_BAD_ASSET_IMAGE);
    } else {
        // Relocate to a specific cube (validated by decoder.init)
        if (!decoder.init(im, destCID))
            return SvmRuntime::fault(F_BAD_ASSET_IMAGE);
    }

    ImageIter iter(decoder, frame, lSrcXY.x, lSrcXY.y, lSize.x, lSize.y);

    if (!SvmMemory::mapRAM(dest, iter.getDestBytes(dest_stride)))
        return SvmRuntime::fault(F_SYSCALL_ADDRESS);

    iter.copyToMem(dest, dest_stride);
}
Beispiel #6
0
void Cursor::load() {
	::Aurora::FileType type;

	Common::SeekableReadStream *img = ResMan.getResource(::Aurora::kResourceCursor, _name, &type);
	if (!img)
		throw Common::Exception("No such cursor resource \"%s\"", _name.c_str());

	_hotspotX = 0;
	_hotspotY = 0;

	ImageDecoder *image;
	// Loading the different image formats
	if      (type == ::Aurora::kFileTypeTGA)
		image = new TGA(*img);
	else if (type == ::Aurora::kFileTypeDDS)
		image = new DDS(*img);
	else if (type == ::Aurora::kFileTypeCUR) {
		WinIconImage *cursor = new WinIconImage(*img);

		if (_hotspotX < 0)
			_hotspotX = cursor->getHotspotX();
		if (_hotspotY < 0)
			_hotspotY = cursor->getHotspotY();

		image = cursor;
	} else {
		delete img;
		throw Common::Exception("Unsupported cursor resource type %d", (int) type);
	}

	delete img;

	_width  = image->getMipMap(0).width;
	_height = image->getMipMap(0).height;

	TXI txi;
	txi.getFeatures().filter = false;

	try {
		Texture *texture = new Texture(image, &txi);

		image = 0;

		try {
			_texture = TextureMan.add(texture, _name);
		} catch(...) {
			delete texture;
			throw;
		}

	} catch (...) {
		delete image;
		throw;
	}

	_hotspotX = CLIP(_hotspotX, 0, _width  - 1);
	_hotspotY = CLIP(_hotspotY, 0, _height - 1);
}
SkBitmap ImageFrameGenerator::tryToResumeDecode(size_t index, const SkISize& scaledSize)
{
    TRACE_EVENT1("blink", "ImageFrameGenerator::tryToResumeDecode", "frame index", static_cast<int>(index));

    ImageDecoder* decoder = 0;
    const bool resumeDecoding = ImageDecodingStore::instance().lockDecoder(this, m_fullSize, &decoder);
    ASSERT(!resumeDecoding || decoder);

    SkBitmap fullSizeImage;
    bool complete = decode(index, &decoder, &fullSizeImage);

    if (!decoder)
        return SkBitmap();

    // If we are not resuming decoding that means the decoder is freshly
    // created and we have ownership. If we are resuming decoding then
    // the decoder is owned by ImageDecodingStore.
    OwnPtr<ImageDecoder> decoderContainer;
    if (!resumeDecoding)
        decoderContainer = adoptPtr(decoder);

    if (fullSizeImage.isNull()) {
        // If decoding has failed, we can save work in the future by
        // ignoring further requests to decode the image.
        m_decodeFailed = decoder->failed();
        if (resumeDecoding)
            ImageDecodingStore::instance().unlockDecoder(this, decoder);
        return SkBitmap();
    }

    bool removeDecoder = false;
    if (complete) {
        // Free as much memory as possible.  For single-frame images, we can
        // just delete the decoder entirely.  For multi-frame images, we keep
        // the decoder around in order to preserve decoded information such as
        // the required previous frame indexes, but if we've reached the last
        // frame we can at least delete all the cached frames.  (If we were to
        // do this before reaching the last frame, any subsequent requested
        // frames which relied on the current frame would trigger extra
        // re-decoding of all frames in the dependency chain.)
        if (!m_isMultiFrame)
            removeDecoder = true;
        else if (index == m_frameCount - 1)
            decoder->clearCacheExceptFrame(kNotFound);
    }

    if (resumeDecoding) {
        if (removeDecoder)
            ImageDecodingStore::instance().removeDecoder(this, decoder);
        else
            ImageDecodingStore::instance().unlockDecoder(this, decoder);
    } else if (!removeDecoder) {
        ImageDecodingStore::instance().insertDecoder(this, decoderContainer.release());
    }
    return fullSizeImage;
}
Beispiel #8
0
Image* ImageFactory::decodeStream(io::InputStream* is, PixelFormat format) {
	Image* bitmap = nullptr;
	ImageDecoder* decoder = ImageDecoder::Factory(is);
	if (decoder) {
//		decoder->disablePreMultipyAlpha();
		decoder->decode(is, bitmap, format);
		delete decoder;
	}
	return bitmap;
}
Beispiel #9
0
/* Create a tinted texture by combining the tint map with the tint colors.
 *
 * This is currently all done here in software and has several drawbacks:
 * - Slow
 * - We're creating lots of uncompressed RBGA texture, so it
 *   takes up a lot of memory, both on the GPU and in system RAM
 *
 * TODO: We really need to do this in shaders in the future.
 */
void ModelNode_NWN2::createTint() {
	if (_tintMap.empty())
		return;

	ImageDecoder *tintMap   = 0;
	Surface      *tintedMap = 0;
	try {
		// Load and uncompress the texture
		tintMap = Texture::loadImage(_tintMap);
		if (tintMap->isCompressed())
			tintMap->decompress();

		const ImageDecoder::MipMap &tintImg = tintMap->getMipMap(0);

		// Create a new target surface with the same dimensions
		tintedMap = new Surface(tintImg.width, tintImg.height);
		ImageDecoder::MipMap &tintedImg = tintedMap->getMipMap();

		// Iterate over all pixels: read values, mix tints, write pixel to target surface
		for (int n = 0; n < tintImg.width * tintImg.height; n++) {
			float srcColor[4], dstColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
			tintImg.getPixel(n, srcColor[0], srcColor[1], srcColor[2], srcColor[3]);

			if (srcColor[3] != 0.0f) {
				// Mix using the value and the alpha components as intensities
				// TODO: Verify how the mixing is actually done in NWN2!
				for (int i = 0; i < 3; i++) {
					for (int j = 0; j < 3; j++)
						dstColor[j] += _tint[i][j] * srcColor[i] * _tint[i][3] * srcColor[3] * _diffuse[i];
				}
			} else
				// Source alpha is 0.0f: No tinting for this pixel
				for (int i = 0; i < 3; i++)
					dstColor[i] = _diffuse[i] * _tint[i][3];

			tintedImg.setPixel(n, dstColor[0], dstColor[1], dstColor[2], dstColor[3]);
		}

	} catch (...) {
		delete tintMap;
		delete tintedMap;
		return;
	}

	delete tintMap;

	// And add the new texture to the TextureManager
	TextureHandle tintedTexture = TextureMan.add(Texture::create(tintedMap));

	_textures.push_back(tintedTexture);
	_tintedMapIndex = _textures.size() - 1;
}
const ScaledImageFragment* ImageFrameGenerator::tryToResumeDecodeAndScale(const SkISize& scaledSize, size_t index)
{
    TRACE_EVENT1("webkit", "ImageFrameGenerator::tryToResumeDecodeAndScale", "index", static_cast<int>(index));

    ImageDecoder* decoder = 0;
    const bool resumeDecoding = ImageDecodingStore::instance()->lockDecoder(this, m_fullSize, &decoder);
    ASSERT(!resumeDecoding || decoder);

    OwnPtr<ScaledImageFragment> fullSizeImage = decode(index, &decoder);

    if (!decoder)
        return 0;

    // If we are not resuming decoding that means the decoder is freshly
    // created and we have ownership. If we are resuming decoding then
    // the decoder is owned by ImageDecodingStore.
    OwnPtr<ImageDecoder> decoderContainer;
    if (!resumeDecoding)
        decoderContainer = adoptPtr(decoder);

    if (!fullSizeImage) {
        // If decode has failed and resulted an empty image we can save work
        // in the future by returning early.
        m_decodeFailedAndEmpty = !m_isMultiFrame && decoder->failed();

        if (resumeDecoding)
            ImageDecodingStore::instance()->unlockDecoder(this, decoder);
        return 0;
    }

    const ScaledImageFragment* cachedImage = ImageDecodingStore::instance()->insertAndLockCache(this, fullSizeImage.release());

    // If the image generated is complete then there is no need to keep
    // the decoder. The exception is multi-frame decoder which can generate
    // multiple complete frames.
    const bool removeDecoder = cachedImage->isComplete() && !m_isMultiFrame;

    if (resumeDecoding) {
        if (removeDecoder)
            ImageDecodingStore::instance()->removeDecoder(this, decoder);
        else
            ImageDecodingStore::instance()->unlockDecoder(this, decoder);
    } else if (!removeDecoder) {
        ImageDecodingStore::instance()->insertDecoder(this, decoderContainer.release(), DiscardablePixelRef::isDiscardable(cachedImage->bitmap().pixelRef()));
    }

    if (m_fullSize == scaledSize)
        return cachedImage;
    return tryToScale(cachedImage, scaledSize, index);
}
TEST_F(ImageFrameGeneratorTest, incompleteBitmapCopied)
{
    setFrameStatus(ImageFrame::FramePartial);

    const ScaledImageFragment* tempImage= m_generator->decodeAndScale(fullSize());
    EXPECT_FALSE(tempImage->isComplete());
    EXPECT_EQ(1, m_frameBufferRequestCount);

    ImageDecoder* tempDecoder = 0;
    EXPECT_TRUE(ImageDecodingStore::instance()->lockDecoder(m_generator.get(), fullSize(), &tempDecoder));
    ASSERT_TRUE(tempDecoder);
    EXPECT_NE(tempDecoder->frameBufferAtIndex(0)->getSkBitmap().getPixels(), tempImage->bitmap().getPixels());
    ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
    ImageDecodingStore::instance()->unlockDecoder(m_generator.get(), tempDecoder);
}
void _SYS_image_BG0Draw(struct _SYSAttachedVideoBuffer *vbuf,
    const _SYSAssetImage *im, uint16_t addr, unsigned frame)
{
    if (!isAligned(vbuf) || !isAligned(im))
        return SvmRuntime::fault(F_SYSCALL_ADDR_ALIGN);

    if (!SvmMemory::mapRAM(vbuf))
        return SvmRuntime::fault(F_SYSCALL_ADDRESS);

    ImageDecoder decoder;
    if (!decoder.init(im, vbuf->cube))
        return SvmRuntime::fault(F_BAD_ASSET_IMAGE);

    ImageIter iter(decoder, frame);
    iter.copyToVRAM(vbuf->vbuf, addr, _SYS_VRAM_BG0_WIDTH);
}
Beispiel #13
0
SkBitmap ImageFrameGenerator::tryToResumeDecode(const SkISize& scaledSize, size_t index)
{
    TRACE_EVENT1("blink", "ImageFrameGenerator::tryToResumeDecodeAndScale", "index", static_cast<int>(index));

    ImageDecoder* decoder = 0;
    const bool resumeDecoding = ImageDecodingStore::instance()->lockDecoder(this, m_fullSize, &decoder);
    ASSERT(!resumeDecoding || decoder);

    SkBitmap fullSizeImage;
    bool complete = decode(index, &decoder, &fullSizeImage);

    if (!decoder)
        return SkBitmap();

    // If we are not resuming decoding that means the decoder is freshly
    // created and we have ownership. If we are resuming decoding then
    // the decoder is owned by ImageDecodingStore.
    OwnPtr<ImageDecoder> decoderContainer;
    if (!resumeDecoding)
        decoderContainer = adoptPtr(decoder);

    if (fullSizeImage.isNull()) {
        // If decode has failed and resulted an empty image we can save work
        // in the future by returning early.
        m_decodeFailedAndEmpty = !m_isMultiFrame && decoder->failed();

        if (resumeDecoding)
            ImageDecodingStore::instance()->unlockDecoder(this, decoder);
        return SkBitmap();
    }

    // If the image generated is complete then there is no need to keep
    // the decoder. The exception is multi-frame decoder which can generate
    // multiple complete frames.
    const bool removeDecoder = complete && !m_isMultiFrame;

    if (resumeDecoding) {
        if (removeDecoder)
            ImageDecodingStore::instance()->removeDecoder(this, decoder);
        else
            ImageDecodingStore::instance()->unlockDecoder(this, decoder);
    } else if (!removeDecoder) {
        ImageDecodingStore::instance()->insertDecoder(this, decoderContainer.release());
    }
    return fullSizeImage;
}
Beispiel #14
0
ImageDecoder *Texture::loadImage(Common::SeekableReadStream *imageStream, ::Aurora::FileType type,
                                 TXI *txi) {

	// Check for a cube map, but only those that don't use a file for each side
	const bool isCubeMap = txi && txi->getFeatures().cube && (txi->getFeatures().fileRange == 0);

	ImageDecoder *image = 0;
	try {
		// Loading the different image formats
		if      (type == ::Aurora::kFileTypeTGA)
			image = new TGA(*imageStream, isCubeMap);
		else if (type == ::Aurora::kFileTypeDDS)
			image = new DDS(*imageStream);
		else if (type == ::Aurora::kFileTypeTPC)
			image = new TPC(*imageStream);
		else if (type == ::Aurora::kFileTypeTXB)
			image = new TXB(*imageStream);
		else if (type == ::Aurora::kFileTypeSBM)
			image = new SBM(*imageStream);
		else if (type == ::Aurora::kFileTypeXEOSITEX)
			image = new XEOSITEX(*imageStream);
		else
			throw Common::Exception("Unsupported image resource type %d", (int) type);

		if (image->getMipMapCount() < 1)
			throw Common::Exception("Texture has no images");

		// Decompress
		if (GfxMan.needManualDeS3TC())
			image->decompress();

	} catch (...) {
		delete image;
		delete imageStream;

		throw;
	}

	delete imageStream;
	return image;
}
TEST_F(ImageFrameGeneratorTest, frameHasAlpha)
{
    setFrameStatus(ImageFrame::FramePartial);

    char buffer[100 * 100 * 4];
    m_generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4);
    EXPECT_TRUE(m_generator->hasAlpha(0));
    EXPECT_EQ(1, m_decodeRequestCount);

    ImageDecoder* tempDecoder = 0;
    EXPECT_TRUE(ImageDecodingStore::instance().lockDecoder(m_generator.get(), fullSize(), &tempDecoder));
    ASSERT_TRUE(tempDecoder);
    tempDecoder->frameBufferAtIndex(0)->setHasAlpha(false);
    ImageDecodingStore::instance().unlockDecoder(m_generator.get(), tempDecoder);
    EXPECT_EQ(2, m_decodeRequestCount);

    setFrameStatus(ImageFrame::FrameComplete);
    m_generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4);
    EXPECT_EQ(3, m_decodeRequestCount);
    EXPECT_FALSE(m_generator->hasAlpha(0));
}
Beispiel #16
0
ImageDecoder *Texture::loadImage(Common::SeekableReadStream *imageStream, ::Aurora::FileType type) {
	ImageDecoder *image = 0;
	try {
		// Loading the different image formats
		if      (type == ::Aurora::kFileTypeTGA)
			image = new TGA(*imageStream);
		else if (type == ::Aurora::kFileTypeDDS)
			image = new DDS(*imageStream);
		else if (type == ::Aurora::kFileTypeTPC)
			image = new TPC(*imageStream);
		else if (type == ::Aurora::kFileTypeTXB)
			image = new TXB(*imageStream);
		else if (type == ::Aurora::kFileTypeSBM)
			image = new SBM(*imageStream);
		else if (type == ::Aurora::kFileTypeXEOSITEX)
			image = new XEOSITEX(*imageStream);
		else
			throw Common::Exception("Unsupported image resource type %d", (int) type);

		if (image->getMipMapCount() < 1)
			throw Common::Exception("Texture has no images");

		// Decompress
		if (GfxMan.needManualDeS3TC())
			image->decompress();

	} catch (...) {
		delete image;
		delete imageStream;

		throw;
	}

	delete imageStream;
	return image;
}
SkBitmap ImageFrameGenerator::tryToResumeDecode(const SkISize& scaledSize, size_t index)
{
    TRACE_EVENT1("blink", "ImageFrameGenerator::tryToResumeDecodeAndScale", "index", static_cast<int>(index));

    ImageDecoder* decoder = 0;
    const bool resumeDecoding = ImageDecodingStore::instance().lockDecoder(this, m_fullSize, &decoder);
    ASSERT(!resumeDecoding || decoder);

    SkBitmap fullSizeImage;
    bool complete = decode(index, &decoder, &fullSizeImage);

    if (!decoder)
        return SkBitmap();
    if (index >= m_frameComplete.size())
        m_frameComplete.resize(index + 1);
    m_frameComplete[index] = complete;

    // If we are not resuming decoding that means the decoder is freshly
    // created and we have ownership. If we are resuming decoding then
    // the decoder is owned by ImageDecodingStore.
    OwnPtr<ImageDecoder> decoderContainer;
    if (!resumeDecoding)
        decoderContainer = adoptPtr(decoder);

    if (fullSizeImage.isNull()) {
        // If decode has failed and resulted an empty image we can save work
        // in the future by returning early.
        m_decodeFailedAndEmpty = !m_isMultiFrame && decoder->failed();

        if (resumeDecoding)
            ImageDecodingStore::instance().unlockDecoder(this, decoder);
        return SkBitmap();
    }

    // If the image generated is complete then there is no need to keep
    // the decoder. For multi-frame images, if all frames in the image are
    // decoded, we remove the decoder.
    bool removeDecoder;

    if (m_isMultiFrame) {
        size_t decodedFrameCount = 0;
        for (Vector<bool>::iterator it = m_frameComplete.begin(); it != m_frameComplete.end(); ++it) {
            if (*it)
                decodedFrameCount++;
        }
        removeDecoder = m_frameCount && (decodedFrameCount == m_frameCount);
    } else {
        removeDecoder = complete;
    }

    if (resumeDecoding) {
        if (removeDecoder) {
            ImageDecodingStore::instance().removeDecoder(this, decoder);
            m_frameComplete.clear();
        } else {
            ImageDecodingStore::instance().unlockDecoder(this, decoder);
        }
    } else if (!removeDecoder) {
        ImageDecodingStore::instance().insertDecoder(this, decoderContainer.release());
    }
    return fullSizeImage;
}
Beispiel #18
0
static void*
imdecode_( const Mat& buf, int flags, int hdrtype, Mat* mat=0 )
{
    CV_Assert(buf.data && buf.isContinuous());
    IplImage* image = 0;
    CvMat *matrix = 0;
    Mat temp, *data = &temp;
    string filename;

    ImageDecoder decoder = findDecoder(buf);
    if( decoder.empty() )
        return 0;

    if( !decoder->setSource(buf) )
    {
        filename = tempfile();
        FILE* f = fopen( filename.c_str(), "wb" );
        if( !f )
            return 0;
        size_t bufSize = buf.cols*buf.rows*buf.elemSize();
        fwrite( &buf.data[0], 1, bufSize, f );
        fclose(f);
        decoder->setSource(filename);
    }

    if( !decoder->readHeader() )
    {
        if( !filename.empty() )
            remove(filename.c_str());
        return 0;
    }

    CvSize size;
    size.width = decoder->width();
    size.height = decoder->height();

    int type = decoder->type();
    if( flags != -1 )
    {
        if( (flags & CV_LOAD_IMAGE_ANYDEPTH) == 0 )
            type = CV_MAKETYPE(CV_8U, CV_MAT_CN(type));

        if( (flags & CV_LOAD_IMAGE_COLOR) != 0 ||
                ((flags & CV_LOAD_IMAGE_ANYCOLOR) != 0 && CV_MAT_CN(type) > 1) )
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 3);
        else
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 1);
    }

    if( hdrtype == LOAD_CVMAT || hdrtype == LOAD_MAT )
    {
        if( hdrtype == LOAD_CVMAT )
        {
            matrix = cvCreateMat( size.height, size.width, type );
            temp = cvarrToMat(matrix);
        }
        else
        {
            mat->create( size.height, size.width, type );
            data = mat;
        }
    }
    else
    {
        image = cvCreateImage( size, cvIplDepth(type), CV_MAT_CN(type) );
        temp = cvarrToMat(image);
    }

    bool code = decoder->readData( *data );
    if( !filename.empty() )
        remove(filename.c_str());

    if( !code )
    {
        cvReleaseImage( &image );
        cvReleaseMat( &matrix );
        if( mat )
            mat->release();
        return 0;
    }

    return hdrtype == LOAD_CVMAT ? (void*)matrix :
           hdrtype == LOAD_IMAGE ? (void*)image : (void*)mat;
}
Beispiel #19
0
static void*
imread_( const string& filename, int flags, int hdrtype, Mat* mat=0 )
{
    IplImage* image = 0;
    CvMat *matrix = 0;
    Mat temp, *data = &temp;

    ImageDecoder decoder = findDecoder(filename);
    if( decoder.empty() )
        return 0;
    decoder->setSource(filename);
    if( !decoder->readHeader() )
        return 0;

    CvSize size;
    size.width = decoder->width();
    size.height = decoder->height();

    int type = decoder->type();
    if( flags != -1 )
    {
        if( (flags & CV_LOAD_IMAGE_ANYDEPTH) == 0 )
            type = CV_MAKETYPE(CV_8U, CV_MAT_CN(type));

        if( (flags & CV_LOAD_IMAGE_COLOR) != 0 ||
                ((flags & CV_LOAD_IMAGE_ANYCOLOR) != 0 && CV_MAT_CN(type) > 1) )
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 3);
        else
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 1);
    }

    if( hdrtype == LOAD_CVMAT || hdrtype == LOAD_MAT )
    {
        if( hdrtype == LOAD_CVMAT )
        {
            matrix = cvCreateMat( size.height, size.width, type );
            temp = cvarrToMat(matrix);
        }
        else
        {
            mat->create( size.height, size.width, type );
            data = mat;
        }
    }
    else
    {
        image = cvCreateImage( size, cvIplDepth(type), CV_MAT_CN(type) );
        temp = cvarrToMat(image);
    }

    if( !decoder->readData( *data ))
    {
        cvReleaseImage( &image );
        cvReleaseMat( &matrix );
        if( mat )
            mat->release();
        return 0;
    }

    return hdrtype == LOAD_CVMAT ? (void*)matrix :
           hdrtype == LOAD_IMAGE ? (void*)image : (void*)mat;
}
Beispiel #20
0
static void*
imdecode_( const Vector<uchar>& buf, int flags, int hdrtype, Mat* mat=0 )
{
    IplImage* image = 0;
    CvMat *matrix = 0;
    Mat temp, *data = &temp;
    char fnamebuf[L_tmpnam];
    const char* filename = 0;

    ImageDecoder decoder = findDecoder(buf);
    if( !decoder.obj )
        return 0;

    if( !decoder->setSource(buf) )
    {
        filename = tmpnam(fnamebuf);
        FILE* f = fopen( filename, "wb" );
        if( !f )
            return 0;
        fwrite( &buf[0], 1, buf.size(), f );
        fclose(f);
        decoder->setSource(filename);
    }

    if( !decoder->readHeader() )
    {
        if( filename )
            unlink(filename);
        return 0;
    }

    CvSize size;
    size.width = decoder->width();
    size.height = decoder->height();

    int type = decoder->type();
    if( flags != -1 )
    {
        if( (flags & CV_LOAD_IMAGE_ANYDEPTH) == 0 )
            type = CV_MAKETYPE(CV_8U, CV_MAT_CN(type));

        if( (flags & CV_LOAD_IMAGE_COLOR) != 0 ||
           ((flags & CV_LOAD_IMAGE_ANYCOLOR) != 0 && CV_MAT_CN(type) > 1) )
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 3);
        else
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 1);
    }

    if( hdrtype == LOAD_CVMAT || hdrtype == LOAD_MAT )
    {
        if( hdrtype == LOAD_CVMAT )
        {
            matrix = cvCreateMat( size.height, size.width, type );
            temp = cvarrToMat(matrix);
        }
        else
        {
            mat->create( size.height, size.width, type );
            data = mat;
        }
    }
    else
    {
        image = cvCreateImage( size, cvIplDepth(type), CV_MAT_CN(type) );
        temp = cvarrToMat(image);
    }

    bool code = decoder->readData( *data );
    if( filename )
        unlink(filename);

    if( !code )
    {
        cvReleaseImage( &image );
        cvReleaseMat( &matrix );
        if( mat )
            mat->release();
        return 0;
    }

    return hdrtype == LOAD_CVMAT ? (void*)matrix :
        hdrtype == LOAD_IMAGE ? (void*)image : (void*)mat;
}
Beispiel #21
0
/**
* Read an image into memory and return the information
*
* @param[in] filename File to load
* @param[in] flags Flags
* @param[in] mats Reference to C++ vector<Mat> object to hold the images
*
*/
static bool
imreadmulti_(const String& filename, int flags, std::vector<Mat>& mats)
{
    /// Search for the relevant decoder to handle the imagery
    ImageDecoder decoder;

#ifdef HAVE_GDAL
    if (flags != IMREAD_UNCHANGED && (flags & IMREAD_LOAD_GDAL) == IMREAD_LOAD_GDAL){
        decoder = GdalDecoder().newDecoder();
    }
    else{
#endif
        decoder = findDecoder(filename);
#ifdef HAVE_GDAL
    }
#endif

    /// if no decoder was found, return nothing.
    if (!decoder){
        return 0;
    }

    /// set the filename in the driver
    decoder->setSource(filename);

    // read the header to make sure it succeeds
    if (!decoder->readHeader())
        return 0;

    for (;;)
    {
        // grab the decoded type
        int type = decoder->type();
        if( (flags & IMREAD_LOAD_GDAL) != IMREAD_LOAD_GDAL && flags != IMREAD_UNCHANGED )
        {
            if ((flags & CV_LOAD_IMAGE_ANYDEPTH) == 0)
                type = CV_MAKETYPE(CV_8U, CV_MAT_CN(type));

            if ((flags & CV_LOAD_IMAGE_COLOR) != 0 ||
                ((flags & CV_LOAD_IMAGE_ANYCOLOR) != 0 && CV_MAT_CN(type) > 1))
                type = CV_MAKETYPE(CV_MAT_DEPTH(type), 3);
            else
                type = CV_MAKETYPE(CV_MAT_DEPTH(type), 1);
        }

        // read the image data
        Mat mat(decoder->height(), decoder->width(), type);
        if (!decoder->readData(mat))
        {
            // optionally rotate the data if EXIF' orientation flag says so
            if( (flags & IMREAD_IGNORE_ORIENTATION) == 0 && flags != IMREAD_UNCHANGED )
            {
                ApplyExifOrientation(filename, mat);
            }

            break;
        }

        mats.push_back(mat);
        if (!decoder->nextPage())
        {
            break;
        }
    }

    return !mats.empty();
}
Beispiel #22
0
/**
 * Read an image into memory and return the information
 *
 * @param[in] filename File to load
 * @param[in] flags Flags
 * @param[in] hdrtype { LOAD_CVMAT=0,
 *                      LOAD_IMAGE=1,
 *                      LOAD_MAT=2
 *                    }
 * @param[in] mat Reference to C++ Mat object (If LOAD_MAT)
 * @param[in] scale_denom Scale value
 *
*/
static void*
imread_( const String& filename, int flags, int hdrtype, Mat* mat=0 )
{
    IplImage* image = 0;
    CvMat *matrix = 0;
    Mat temp, *data = &temp;

    /// Search for the relevant decoder to handle the imagery
    ImageDecoder decoder;

#ifdef HAVE_GDAL
    if(flags != IMREAD_UNCHANGED && (flags & IMREAD_LOAD_GDAL) == IMREAD_LOAD_GDAL ){
        decoder = GdalDecoder().newDecoder();
    }else{
#endif
        decoder = findDecoder( filename );
#ifdef HAVE_GDAL
    }
#endif

    /// if no decoder was found, return nothing.
    if( !decoder ){
        return 0;
    }

    int scale_denom = 1;
    if( flags > IMREAD_LOAD_GDAL )
    {
    if( flags & IMREAD_REDUCED_GRAYSCALE_2 )
        scale_denom = 2;
    else if( flags & IMREAD_REDUCED_GRAYSCALE_4 )
        scale_denom = 4;
    else if( flags & IMREAD_REDUCED_GRAYSCALE_8 )
        scale_denom = 8;
    }

    /// set the scale_denom in the driver
    decoder->setScale( scale_denom );

    /// set the filename in the driver
    decoder->setSource( filename );

   // read the header to make sure it succeeds
   if( !decoder->readHeader() )
        return 0;

    // established the required input image size
    CvSize size;
    size.width = decoder->width();
    size.height = decoder->height();

    // grab the decoded type
    int type = decoder->type();
    if( (flags & IMREAD_LOAD_GDAL) != IMREAD_LOAD_GDAL && flags != IMREAD_UNCHANGED )
    {
        if( (flags & CV_LOAD_IMAGE_ANYDEPTH) == 0 )
            type = CV_MAKETYPE(CV_8U, CV_MAT_CN(type));

        if( (flags & CV_LOAD_IMAGE_COLOR) != 0 ||
           ((flags & CV_LOAD_IMAGE_ANYCOLOR) != 0 && CV_MAT_CN(type) > 1) )
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 3);
        else
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 1);
    }

    if( hdrtype == LOAD_CVMAT || hdrtype == LOAD_MAT )
    {
        if( hdrtype == LOAD_CVMAT )
        {
            matrix = cvCreateMat( size.height, size.width, type );
            temp = cvarrToMat( matrix );
        }
        else
        {
            mat->create( size.height, size.width, type );
            data = mat;
        }
    }
    else
    {
        image = cvCreateImage( size, cvIplDepth(type), CV_MAT_CN(type) );
        temp = cvarrToMat( image );
    }

    // read the image data
    if( !decoder->readData( *data ))
    {
        cvReleaseImage( &image );
        cvReleaseMat( &matrix );
        if( mat )
            mat->release();
        return 0;
    }

    if( decoder->setScale( scale_denom ) > 1 ) // if decoder is JpegDecoder then decoder->setScale always returns 1
    {
        resize( *mat, *mat, Size( size.width / scale_denom, size.height / scale_denom ) );
    }

    return hdrtype == LOAD_CVMAT ? (void*)matrix :
        hdrtype == LOAD_IMAGE ? (void*)image : (void*)mat;
}
AnimatedGif::AnimatedGif(const WCHAR *name, const WCHAR *type, ImageDecoder &imageDecoder)
{
	imageDecoder.loadGifFromResource(name, type, frames);
}
Beispiel #24
0
    void LambdaTask::DoDecodeImage()
    {
        LOG_TRACE(__FUNCTION__);
       
        char* ptrchTmpImg;
        char* ptrchTmpImg1;
	ptrchTmpImg = 0; // Null pointer initially
	ptrchTmpImg1 = 0;
        ImageDecoder* objDecoder = new ImageDecoder(m_vCurrentChip);
        ImageDecoder* objDecoder1 = new ImageDecoder(m_vCurrentChip);

        short* ptrshDecodedImg;
        short* ptrshDecodedImg1;
        int* ptrnDecodedImg = new int[m_nDecodedImageSize];
        int* ptrnFinishedImg;

        DistortionCorrector<short> *objDC = new DistortionCorrector<short>(m_vNIndex,m_vNNominator,(int)pow(2,12));
        DistortionCorrector<int> *objDC1 = new DistortionCorrector<int>(m_vNIndex,m_vNNominator,(int)pow(2,24));
        
        while(true)
        {
            usleep(20);

            boost::unique_lock<boost::mutex> lock(*m_boostMtx);
            bool bVal = m_objSys->SysExit();
            string strOperationMode =m_objSys->GetOperationMode();
            int nDistortionCorr = m_objSys->GetDistortionCorrecttionMethod();
            lock.unlock();

            if(bVal)
                break;

            if(*m_enumTargetPriority > m_enumPriority) // If priority lower, throttle back task
            {
                usleep(10000);
                continue;
            }

            //continuousReadWrite
            if(strOperationMode == OPERATION_MODE_12)
            {
                if((m_objMemPoolRaw->GetStoredImageNumbers() == 0) || (m_objMemPoolDecodedShort->IsFull()))
                {
                    usleep(50);
                    continue;
                }	  

		
                short shErrCode = 0;
                long lFrameNo = 0;    
                if(m_objMemPoolRaw->GetImage(ptrchTmpImg,lFrameNo,shErrCode))
		{
                    objDecoder->SetRawImage(ptrchTmpImg);
                    ptrshDecodedImg = objDecoder->RunDecodingImg();


                    if(nDistortionCorr == 1)
                    {
                        //distortion correction
                        short* pShImgOut = objDC->RunDistortCorrect(ptrshDecodedImg);
                        ptrshDecodedImg = pShImgOut;
                    }
            
                    if(m_objMemPoolDecodedShort->GetFirstFrameNo() == -1)
                    {
                        long lFristFrame = m_objMemPoolRaw->GetFirstFrameNo();
                
                        //if lFristFrame is -1, means it is single link version
                        if(lFristFrame!=-1)
                            m_objMemPoolDecodedShort->SetFirstFrameNo(lFristFrame);
                    }    
                    //cout<<lFrameNo<<":is taken for decoding"<<endl;

                    while(true)
                    {
                        usleep(20);

                        lock.lock();
                        bool bIsAcq = m_objSys->GetAcquisitionStop();
                        lock.unlock();
                
                        if(bIsAcq)
                            break;
	    
                        if(m_objMemPoolDecodedShort->SetImage(ptrshDecodedImg,lFrameNo,shErrCode,true) == true)
			  {
                              break;
			  }
                    }
                }
                
            }
            else if(strOperationMode == OPERATION_MODE_24)
            {
                if((m_objMemPoolRaw->GetStoredImageNumbers() < 2) || (m_objMemPoolDecodedInt->IsFull()))
                {
                    usleep(50);
                    continue;
                }	  

                short shErrCode = 0;
                long lFrameNo = 0;
                short shErrCode1 = 0;
                long lFrameNo1 = 0;
                
                if(m_objMemPoolRaw->Get2Image(ptrchTmpImg,lFrameNo,shErrCode,ptrchTmpImg1,lFrameNo1,shErrCode1))
                {
                
                    objDecoder->SetRawImage(ptrchTmpImg);
                    ptrshDecodedImg = objDecoder->RunDecodingImg();

                    objDecoder1->SetRawImage(ptrchTmpImg1);
                    ptrshDecodedImg1 = objDecoder1->RunDecodingImg();

                    for(int i=0;i<m_nDecodedImageSize;i++)
                        ptrnDecodedImg[i] = ((int)ptrshDecodedImg[i])+(((int)ptrshDecodedImg1[i])*4096);
                    lFrameNo = lFrameNo1/2;
                    shErrCode = shErrCode<=shErrCode1?shErrCode:shErrCode1;
                    ptrnFinishedImg = ptrnDecodedImg;
                
                    if(nDistortionCorr == 1)
                    {
                        //distortion correction
                        int* pNImgOut = objDC1->RunDistortCorrect(ptrnDecodedImg);
                        ptrnFinishedImg = pNImgOut;
                    }
                
                    if(m_objMemPoolDecodedInt->GetFirstFrameNo() == -1)
                    {
                        long lFristFrame = m_objMemPoolRaw->GetFirstFrameNo();
                
                        //if lFristFrame is -1, means it is single link version
                        if(lFristFrame!=-1)
                            m_objMemPoolDecodedInt->SetFirstFrameNo((lFristFrame+1)/2);
                    }

                    while(true)
                    {
                        usleep(20);

                        lock.lock();
                        bool bIsAcq = m_objSys->GetAcquisitionStop();
                        lock.unlock();
                
                        if(bIsAcq)
                            break;
	    
                        if(m_objMemPoolDecodedInt->SetImage(ptrnFinishedImg,lFrameNo,shErrCode,true) == true)
                            break;
                    }
                }
                
            }
            
            
        }///end loop
        
        delete objDecoder;
        delete objDecoder1;
        delete ptrnDecodedImg;

        delete objDC;

        delete objDC1;

        LOG_INFOS("Do decoding thread exits");	
    }