Example #1
0
void slice(head *header,pi **a,pinfo *info,int n){
	int margin=15;
	int hmargin=20;
	long unsigned sx=margin;
	long unsigned ex=header->width/n-hmargin;
	for (int i = 0; i < n; ++i)
	{
		char name[13];
		snprintf(name,sizeof(name),"output1%d.bmp",i);
		pi **ab=crop(header,a,sx,header->height-margin,sx+ex,margin);
		head *newH=changeHeader(header,ex,header->height-2*margin);
		blackWhite(ab,ex,header->height-2*margin);
		writeImage(ab,newH,info,name);
		doTess(name);
	//	free(ab);
		sx+=ex+hmargin;
	}
}
Example #2
0
	void writeImage(const StorageKey &location, const ImagePtr &image) {
		if (image->isNull() || !image->loaded()) return;
		if (_storageMap.constFind(location) != _storageMap.cend()) return;

		QByteArray fmt = image->savedFormat();
		mtpTypeId format = 0;
		if (fmt == "JPG") {
			format = mtpc_storage_fileJpeg;
		} else if (fmt == "PNG") {
			format = mtpc_storage_filePng;
		} else if (fmt == "GIF") {
			format = mtpc_storage_fileGif;
		}
		if (format) {
			image->forget();
			writeImage(location, StorageImageSaved(format, image->savedData()), false);
		}
	}
Example #3
0
File: p1.c Project: akivab/compviz2
int main(int nargin, char** argv){
  if(nargin != 4){
    printf("Usage: p1 <greylevel img> <threshold> <output file>");
    return -1;
  }
  
  im = (Image*) malloc(sizeof(Image));
  thresh = atoi(argv[2]);
  readImage(im, argv[1]);
  int i, j;
  setColors(im, 1);
  for(i = 0; i < getNRows(im); i++){
    for(j = 0; j < getNCols(im); j++){
      setPixel(im, i, j, getPixel(im, i, j) > thresh);
    }
  }
  writeImage(im, argv[3]);
}
Example #4
0
void FaceController::prepareFaceToSave(TriMesh2d mesh, gl::Texture surf, float headScale)
{
	genericName = "surf_"+to_string(facesStoreVector.size()) + ".png";	

	Rectf rect =	mesh.calcBoundingBox();	

	vector<ci::Vec2f> savecords;
	savecords.clear();
	for (int i = 0; i < mesh.getNumVertices(); i++)
		 savecords.push_back(Vec2f( ( mesh.getVertices()[i].x-rect.x1 )/surf.getWidth(), (mesh.getVertices()[i].y -rect.y1)/surf.getHeight())); 	
	
	FaceObject newface;
	newface.setPoints(savecords);
	newface.setTexName(genericName);
	newface.setTexture(surf);

	facesStoreVector.push_back(newface);
	writeImage( getAppPath() /FACE_STORAGE_FOLDER/genericName, surf);
}
Example #5
0
int main(void)
{
	printf("Loading image from '%s'\n", in_filename);
	uint8_t *in_data;
	uint64_t width, height;
	loadImage(in_filename, &in_data, &width, &height);

	uint64_t data_size = width * height * 3;
	uint8_t *out_data = malloc(data_size);
	printf("Configuring DFE with full bitstream\n");

	max_file_t *maxfile = PRImageFilter_init();
	max_engine_t *engine = max_load(maxfile, "*");

	printf("Running DFE\n");
	PRImageFilter_actions_t myaction = { data_size, in_data, out_data };
	PRImageFilter_run(engine, &myaction);

	printf("Partially reconfiguring DFE\n");
	max_reconfig_partial_bitstream(engine, "EdgeLaplaceKernel");
	max_reconfig_partial_bitstream(engine, "ThresholdKernel");

	printf("Running DFE\n");
	myaction.instream_input = out_data;
	PRImageFilter_run(engine, &myaction);

	max_unload(engine);

	printf("Saving image to '%s'\n", out_filename);
	writeImage(out_filename, out_data, width, height);

	printf("Checking result against '%s'\n", golden_filename);
	int ret = checkResult(out_data);
	if (!ret)
		printf("Result correct\n");
	else
		printf("Result incorrect\n");

	free(in_data);
	free(out_data);

	return ret;
}
void circles()
{
	// Find edges
	Image i = readImage("circles.ppm");
	GradientAndEdges gradientAndEdges = findGradientAndEdges(i, 5, 5, 3, 20);

	// Create buffer
	int bufferSize = 50;
	Image result = newImage(1, i.w + bufferSize * 2, i.h + bufferSize * 2);
	clearImage(result);

	// Find circles
	findCircles(gradientAndEdges, result, 32, 12, bufferSize, 15, 10);
	findCircles(gradientAndEdges, result, 16, 5, bufferSize, 15, 10);
	findCircles(gradientAndEdges, result, 48, 3, bufferSize, 51, 20);

	// Show result
	writeImage(result, "result.pgm");
	return;
}
Example #7
0
/*!
 * Adds an image to the pdf and return the pdf-object id. Returns -1 if adding the image failed.
 */
int QPdfEnginePrivate::addImage(const QImage &img, bool *bitmap, qint64 serial_no)
{
    if (img.isNull())
        return -1;

    int object = imageCache.value(serial_no);
    if(object)
        return object;

    QImage image = img;
    QImage::Format format = image.format();
    if (image.depth() == 1 && *bitmap && img.colorTable().size() == 2
        && img.colorTable().at(0) == QColor(Qt::black).rgba()
        && img.colorTable().at(1) == QColor(Qt::white).rgba())
    {
        if (format == QImage::Format_MonoLSB)
            image = image.convertToFormat(QImage::Format_Mono);
        format = QImage::Format_Mono;
    } else {
        *bitmap = false;
        if (format != QImage::Format_RGB32 && format != QImage::Format_ARGB32) {
            image = image.convertToFormat(QImage::Format_ARGB32);
            format = QImage::Format_ARGB32;
        }
    }

    int w = image.width();
    int h = image.height();
    int d = image.depth();

    if (format == QImage::Format_Mono) {
        int bytesPerLine = (w + 7) >> 3;
        QByteArray data;
        data.resize(bytesPerLine * h);
        char *rawdata = data.data();
        for (int y = 0; y < h; ++y) {
            memcpy(rawdata, image.scanLine(y), bytesPerLine);
            rawdata += bytesPerLine;
        }
        object = writeImage(data, w, h, d, 0, 0);
    } else {
Example #8
0
File: p3.c Project: akivab/compviz3
int main(int nargin, char** argv) {
    if(nargin != 5) {
        printf("Usage: p1 <img> <hough img> <hough thresh> <line-detected output>\n");
        return -1;
    }

    Image* im = (Image*) malloc(sizeof(Image));
    Image* hough = (Image*) malloc(sizeof(Image));

    readImage(im, argv[1]);
    readImage(hough, argv[2]);

    int i, j, nR, nC;
    nR = getNRows(im);
    nC = getNCols(im);

    int thresh = atoi(argv[3]);
    int p = 0;
    for(i=0; i < getNRows(hough); i++)
        for(j=0; j < getNCols(hough); j++) {
            p = getPixel(hough,i,j);

            if(p > thresh) {
                // draw our line
                // the i'th value is our p value. j'th is theta + 90 degrees.
                // equation was: p = - x sin(t) + y cos(t)
                // now we have: y = x tan(t) + p/cos(t)
                float t = j - 180;
                float p = i;
                float m = tan(t / 180 * PI);
                float b = p / cos(t / 180 * PI);

                line(im, (int) (m*0+b), 0, (int) (m*nC+b), nC, 0);
            }
        }

    writeImage(im, argv[4]);
    free(im);
    free(hough);
    return 0;
}
Example #9
0
  void writeGetLegendGraphics( QgsServerInterface* serverIface, const QString& version,
                               const QgsServerRequest& request, QgsServerResponse& response )
  {
    Q_UNUSED( version );

    QgsServerRequest::Parameters params = request.parameters();
    QgsRenderer renderer( serverIface, params, getConfigParser( serverIface ) );

    QScopedPointer<QImage> result( renderer.getLegendGraphics() );

    if ( !result.isNull() )
    {
      QString format = params.value( QStringLiteral( "FORMAT" ), QStringLiteral( "PNG" ) );
      writeImage( response, *result,  format, renderer.getImageQuality() );
    }
    else
    {
      throw QgsServiceException( QStringLiteral( "UnknownError" ),
                                 QStringLiteral( "Failed to compute GetLegendGraphics image" ) );
    }
  }
Example #10
0
/**
 * Handle key presses. OpenGL keyboard callback.
 * @param key key code pressed
 * @param x   keyboard pos.
 * @param y   keyboard pos.
 */
void handleKey(unsigned char key, int x, int y) {
    switch (key) {
    //Gracefully exit the program
        case 'q':
        case 'Q':
        case 27:                    // ESC
          exit(EXIT_SUCCESS);
          break;

        case 'r':
        case 'R':
          smartProcess();
          openGLFlip();
          glutPostRedisplay();
          if(canWrite) writeImage();
          break;

        default:
          return;
    }
}
void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform)
{
    const int w = sourceImage.getWidth();
    const int h = sourceImage.getHeight();

    writeClip();

    out << "gsave ";
    writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
                             .scaled (1.0f, -1.0f));

    RectangleList imageClip;
    sourceImage.createSolidAreaMask (imageClip, 0.5f);

    out << "newpath ";
    int itemsOnLine = 0;

    for (RectangleList::Iterator i (imageClip); i.next();)
    {
        if (++itemsOnLine == 6)
        {
            out << '\n';
            itemsOnLine = 0;
        }

        const Rectangle<int>& r = *i.getRectangle();

        out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
    }

    out << " clip newpath\n";

    out << w << ' ' << h << " scale\n";
    out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";

    writeImage (sourceImage, 0, 0, w, h);

    out << "false 3 colorimage grestore\n";
    needToClip = true;
}
Example #12
0
//----------------------------------------------------------------------------
Guido2ImageErrorCodes Guido2Image::guidoPainterToImage( QGuidoPainter * guidoPainter, const char * imageFileName, Guido2ImageImageFormat imageFormat,
	int pageIndex, const QSize& outputSizeConstraint, float zoom, char * errorMsgBuffer, int bufferSize)
{
	Guido2ImageErrorCodes result = GUIDO_2_IMAGE_SUCCESS;
	if ( guidoPainter->isGMNValid() )
	{
		int page = pageIndex;
		if ( page < 0 )  page = 0;
		else if ( page > guidoPainter->pageCount() ) page = guidoPainter->pageCount();
		if ( imageFormat == GUIDO_2_IMAGE_PDF )
			writePDF( guidoPainter, page, imageFileName );
		else
			writeImage(guidoPainter, imageFormat, page, outputSizeConstraint, zoom, imageFileName);
	}
	else
	{
		WRITE_ERROR( errorMsgBuffer, guidoPainter->getLastErrorMessage().toAscii().data(), bufferSize );
		result = GUIDO_2_IMAGE_INVALID_GMN_CODE;
	}
	QGuidoPainter::destroyGuidoPainter( guidoPainter );
	return result;
}
Example #13
0
bool ExportManager::remoteSave(const QUrl &url, const QString &mimetype)
{
    QTemporaryFile tmpFile;

    if (tmpFile.open()) {
        if(!writeImage(&tmpFile, mimetype.toLatin1())) {
            emit errorMessage(i18n("Cannot save screenshot. Error while writing temporary local file."));
            return false;
        }

        KIO::FileCopyJob *uploadJob = KIO::file_copy(QUrl::fromLocalFile(tmpFile.fileName()), url);
        uploadJob->exec();

        if (uploadJob->error() != KJob::NoError) {
            emit errorMessage(i18n("Unable to save image. Could not upload file to remote location."));
            return false;
        }
        return true;
    }

    return false;
}
Example #14
0
File: main.c Project: farosis/gfx
void Render(void)
{
  GLfloat vertex[] = {
    -1, -1, 0,
    -1, 1, 0,
    1, 1, 0,
    1, -1, 0
  };
  GLuint index[] = {
    0, 1, 2
  };

  GLint position = glGetAttribLocation(program, "positionIn");
  glEnableVertexAttribArray(position);
  glVertexAttribPointer(position, 3, GL_FLOAT, 0, 0, vertex);

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glDrawElements(GL_TRIANGLES, sizeof(index)/sizeof(GLuint), GL_UNSIGNED_INT, index);

  glFlush();

  #ifdef _OGLES_30_
  glReadBuffer(GL_COLOR_ATTACHMENT0);
  #endif

  GLubyte result[TARGET_SIZE * TARGET_SIZE * 4] = {0};
  glReadPixels(0, 0, TARGET_SIZE, TARGET_SIZE, GL_RGBA, GL_UNSIGNED_BYTE, result);
  assert(glGetError() == GL_NO_ERROR);
  /*
  int i, j;
  for (i = 0; i < TARGET_SIZE / 8; i++) {
    for (j = 0; j < TARGET_SIZE / 8; j++)
      printf("%08x ", result[i * TARGET_SIZE * 4 + j * 4]);
    printf("\n");
  }
  //*/
  assert(!writeImage("screenshot.png", TARGET_SIZE, TARGET_SIZE, result, "hello"));
}
Example #15
0
void testNoise (void) {
	
	GIMAGE* input = Gtype(readGrey("./TestRepo/00.Test_Images/lena.bmp"));
	GIMAGE* output = createImage(input->width,input->height,1);
	
	double *pdf = new double [NOISE_LENGTH];
	GaussianFilter (NOISE_LENGTH/2, (double)NOISE_LENGTH/3.0, 0, NOISE_LENGTH, pdf); // Gaussian white noise
	
	// Uniform White noise
	//for (int i = 0; i < NOISE_LENGTH; i++)
	// 	pdf [i] = 1.0/NOISE_LENGTH;
		
	// Impulse
	//for (int i = 0; i < NOISE_LENGTH; i++)
	//	pdf [i] = 0;
	//pdf [(int)NOISE_LENGTH-1] = 1;

	double *inv_cdf = inverse_cdf (-NOISE_AMP, NOISE_AMP, NOISE_LENGTH, pdf);
	
	addWhiteNoise (input, NOISE_LENGTH, inv_cdf, output);

	writeImage ("./TestRepo/noise.bmp", output);		
}
Example #16
0
int main(int argc, char **argv)
{
  //printf("Num args is %d\n", argc);
  if (argc < 7) {
    printf("Usage: ras width height x0 y0 x1 y1\n");
    exit(1);
  }
  
  int a[6];
  int i;
  for (i=0; i<6; i++) {
    a[i] = atoi(argv[i+1]);
  }
  
  
  imageData idata = getNewImageData(a[0], a[1]);
  
  rasterLine(idata, a[2], a[3], a[4], a[5]);
  writeImage("out.png", idata);
  
  cleanupImageData(idata);
  return 0;
}
  void writeGetLegendGraphics( QgsServerInterface *serverIface, const QgsProject *project,
                               const QString &version, const QgsServerRequest &request,
                               QgsServerResponse &response )
  {
    Q_UNUSED( version );

    QgsServerRequest::Parameters params = request.parameters();

    QgsWmsParameters wmsParameters( QUrlQuery( request.url() ) );
    QgsRenderer renderer( serverIface, project, wmsParameters );

    std::unique_ptr<QImage> result( renderer.getLegendGraphics() );

    if ( result )
    {
      QString format = params.value( QStringLiteral( "FORMAT" ), QStringLiteral( "PNG" ) );
      writeImage( response, *result,  format, renderer.getImageQuality() );
    }
    else
    {
      throw QgsServiceException( QStringLiteral( "UnknownError" ),
                                 QStringLiteral( "Failed to compute GetLegendGraphics image" ) );
    }
  }
Example #18
0
QUrl ExportManager::tempSave(const QString &mimetype)
{
    // if we already have a temp file saved, use that
    if (mTempFile.isValid()) {
        if (QFile(mTempFile.toLocalFile()).exists()) {
            return mTempFile;
        }
    }

    QTemporaryFile tmpFile(QDir::tempPath() + QDir::separator() + "Spectacle.XXXXXX." + mimetype);
    tmpFile.setAutoRemove(false);
    tmpFile.setPermissions(QFile::ReadUser | QFile::WriteUser);

    if (tmpFile.open()) {
        if(!writeImage(&tmpFile, mimetype.toLatin1())) {
            emit errorMessage(i18n("Cannot save screenshot. Error while writing temporary local file."));
            return QUrl();
        }
        mTempFile = QUrl::fromLocalFile(tmpFile.fileName());
        return mTempFile;
    }

    return QUrl();
}
Example #19
0
void writePecStitches(EmbPattern* pattern, EmbFile* file, const char* fileName)
{
    EmbStitchList* tempStitches = 0;
    EmbRect bounds;
    unsigned char image[38][48];
    int i, flen, currentThreadCount, graphicsOffsetLocation, graphicsOffsetValue, height, width;
    double xFactor, yFactor;
    const char* forwardSlashPos = strrchr(fileName, '/');
    const char* backSlashPos = strrchr(fileName, '\\');
    const char* dotPos = strrchr(fileName, '.');
    const char* start = 0;

    if(!pattern) { embLog_error("format-pec.c writePecStitches(), pattern argument is null\n"); return; }
    if(!file) { embLog_error("format-pec.c writePecStitches(), file argument is null\n"); return; }
    if(!fileName) { embLog_error("format-pec.c writePecStitches(), fileName argument is null\n"); return; }

    if(forwardSlashPos)
    {
        start = forwardSlashPos + 1;
    }
    if(backSlashPos && backSlashPos > start)
    {
        start = backSlashPos + 1;
    }
    if(!start)
    {
        start = fileName;
    }
    binaryWriteBytes(file, "LA:", 3);
    flen = (int)(dotPos - start);

    while(start < dotPos)
    {
        binaryWriteByte(file, (unsigned char)*start);
        start++;
    }
    for(i = 0; i < (int)(16-flen); i++)
    {
        binaryWriteByte(file, (unsigned char)0x20);
    }
    binaryWriteByte(file, 0x0D);
    for(i = 0; i < 12; i++)
    {
        binaryWriteByte(file, (unsigned char)0x20);
    }
    binaryWriteByte(file, (unsigned char)0xFF);
    binaryWriteByte(file, (unsigned char)0x00);
    binaryWriteByte(file, (unsigned char)0x06);
    binaryWriteByte(file, (unsigned char)0x26);

    for(i = 0; i < 12; i++)
    {
        binaryWriteByte(file, (unsigned char)0x20);
    }
    currentThreadCount = embThreadList_count(pattern->threadList);
    binaryWriteByte(file, (unsigned char)(currentThreadCount-1));

    for(i = 0; i < currentThreadCount; i++)
    {
        binaryWriteByte(file, (unsigned char)embThread_findNearestColorInArray(embThreadList_getAt(pattern->threadList, i).color, (EmbThread*)pecThreads, pecThreadCount));
    }
    for(i = 0; i < (int)(0x1CF - currentThreadCount); i++)
    {
        binaryWriteByte(file, (unsigned char)0x20);
    }
    binaryWriteShort(file, (short)0x0000);

    graphicsOffsetLocation = embFile_tell(file);
    /* placeholder bytes to be overwritten */
    binaryWriteByte(file, (unsigned char)0x00);
    binaryWriteByte(file, (unsigned char)0x00);
    binaryWriteByte(file, (unsigned char)0x00);

    binaryWriteByte(file, (unsigned char)0x31);
    binaryWriteByte(file, (unsigned char)0xFF);
    binaryWriteByte(file, (unsigned char)0xF0);

    bounds = embPattern_calcBoundingBox(pattern);

    height = roundDouble(embRect_height(bounds));
    width = roundDouble(embRect_width(bounds));
    /* write 2 byte x size */
    binaryWriteShort(file, (short)width);
    /* write 2 byte y size */
    binaryWriteShort(file, (short)height);

    /* Write 4 miscellaneous int16's */
    binaryWriteShort(file, (short)0x1E0);
    binaryWriteShort(file, (short)0x1B0);

    binaryWriteUShortBE(file, (unsigned short)(0x9000 | -roundDouble(bounds.left)));
    binaryWriteUShortBE(file, (unsigned short)(0x9000 | -roundDouble(bounds.top)));

    pecEncode(file, pattern);
    graphicsOffsetValue = embFile_tell(file) - graphicsOffsetLocation + 2;
    embFile_seek(file, graphicsOffsetLocation, SEEK_SET);

    binaryWriteByte(file, (unsigned char)(graphicsOffsetValue & 0xFF));
    binaryWriteByte(file, (unsigned char)((graphicsOffsetValue >> 8) & 0xFF));
    binaryWriteByte(file, (unsigned char)((graphicsOffsetValue >> 16) & 0xFF));

    embFile_seek(file, 0x00, SEEK_END);

    /* Writing all colors */
    clearImage(image);
    tempStitches = pattern->stitchList;

    yFactor = 32.0 / height;
    xFactor = 42.0 / width;
    while(tempStitches->next)
    {
        int x = roundDouble((tempStitches->stitch.xx - bounds.left) * xFactor) + 3;
        int y = roundDouble((tempStitches->stitch.yy - bounds.top) * yFactor) + 3;
        image[y][x] = 1;
        tempStitches = tempStitches->next;
    }
    writeImage(file, image);

    /* Writing each individual color */
    tempStitches = pattern->stitchList;
    for(i = 0; i < currentThreadCount; i++)
    {
        clearImage(image);
        while(tempStitches->next)
        {
            int x = roundDouble((tempStitches->stitch.xx - bounds.left) * xFactor) + 3;
            int y = roundDouble((tempStitches->stitch.yy - bounds.top) * yFactor) + 3;
            if(tempStitches->stitch.flags & STOP)
            {
                tempStitches = tempStitches->next;
                break;
            }
            image[y][x] = 1;
            tempStitches = tempStitches->next;
        }
        writeImage(file, image);
    }
}
Example #20
0
 bool writeImage(const QImage& img, int quality, const QString &description)
     { return writeImage(img, quality, description, 0, 0); }
Example #21
0
void writeImageNorm(char *fileName, GIMAGE *image, bool printInfo) {
    IMAGE *outImage =  uCharNorm(image);
    writeImage(fileName, outImage, printInfo);
}
Example #22
0
void writeImage( const fs::path &path, const ImageSourceRef &imageSource, ImageTarget::Options options, std::string extension )
{
	writeImage( (DataTargetRef)writeFile( path ), imageSource, options, extension );
}
Example #23
0
 bool writeImage(const QImage& img)
     { return writeImage(img, 0, 0); }
Example #24
0
void GxEPD2_270::drawImage(const uint8_t bitmap[], int16_t x, int16_t y, int16_t w, int16_t h, bool invert, bool mirror_y, bool pgm)
{
  writeImage(bitmap, x, y, w, h, invert, mirror_y, pgm);
  refresh(x, y, w, h);
  writeImageAgain(bitmap, x, y, w, h, invert, mirror_y, pgm);
}
Example #25
0
void WriteIconData::acceptImage(DomImage *image)
{
    writeImage(output, option.indent, image);
}
Example #26
0
int main(int argc, char **argv)
{
    nitf_Reader* reader;                /* The reader object */
    nitf_Writer* writer;                /* The writer object */
    nitf_Record* record;                /* a record object */
    nitf_Record* record2;
    nitf_ListIterator iter;             /* current pos iterator */
    nitf_ListIterator end;              /* end of list iterator */
    nitf_ImageSegment* segment;         /* the image segment */

    NITF_BOOL success;                  /* status bool */

    nitf_IOHandle input_io;             /* input IOHandle */
    nitf_IOHandle output_io;            /* output IOHandle */
    nitf_Error error;                   /* error object */

    /*  Check argv and make sure we are happy  */
    if (argc != 3)
    {
        printf("Usage: %s <input-file> <output-file> \n", argv[0]);
        exit(EXIT_FAILURE);
    }

    input_io = nitf_IOHandle_create(argv[1],
                                    NITF_ACCESS_READONLY,
                                    NITF_OPEN_EXISTING, &error);
    if ( NITF_INVALID_HANDLE(input_io))
    {
        goto CATCH_ERROR;
    }

    output_io = nitf_IOHandle_create(argv[2],
                                     NITF_ACCESS_WRITEONLY,
                                     NITF_CREATE | NITF_TRUNCATE,
                                     &error);

    if ( NITF_INVALID_HANDLE(output_io))
    {
        goto CATCH_ERROR;
    }

    reader = nitf_Reader_construct(&error);
    if (!reader)
    {
        goto CATCH_ERROR;
    }

    writer = nitf_Writer_construct(&error);
    if (!writer)
    {
        goto CATCH_ERROR;
    }

    record = nitf_Record_construct(&error);
    if (!record)
    {
        goto CATCH_ERROR;
    }

    assert(nitf_Reader_read(reader, input_io, record, &error));
    showFileHeader(record->header);

    /*  Write to the file  */
    success = nitf_Writer_writeHeader(writer, record->header, output_io, &error);
    if (!success) goto CATCH_ERROR;


    /*  ------ IMAGES ------  */
    iter = nitf_List_begin(record->images);
    end  = nitf_List_end(record->images);
    while (nitf_ListIterator_notEqualTo(&iter, &end))
    {
        /*  Cast it to an imageSegment...  */
        segment = (nitf_ImageSegment*)nitf_ListIterator_get(&iter);

        /* write the image subheader */
        if (!nitf_Writer_writeImageSubheader(writer,
                                             segment->subheader,
                                             record->header->NITF_FVER->raw,
                                             output_io,
                                             &error))
        {
            goto CATCH_ERROR;
        }

        /* Now, write the image */
        if (!writeImage(segment, input_io, output_io))
        {
            goto CATCH_ERROR;
        }

        nitf_ListIterator_increment(&iter);
    }

    nitf_IOHandle_close(input_io);
    nitf_IOHandle_close(output_io);
    nitf_Record_destruct(&record);
    nitf_Writer_destruct(&writer);

    /*  Open the file we just wrote to, and dump it to screen */
    input_io = nitf_IOHandle_create(argv[2],
                                    NITF_ACCESS_READONLY,
                                    NITF_OPEN_EXISTING,
                                    &error);
    if (NITF_INVALID_HANDLE(input_io))
    {
        goto CATCH_ERROR;
    }

    record2 = nitf_Record_construct(&error);
    if (!record2)
    {
        goto CATCH_ERROR;
    }

    assert(nitf_Reader_readHeader(reader, input_io, record2, &error));
    showFileHeader(record2->header);

    nitf_IOHandle_close(input_io);
    nitf_Record_destruct(&record2);
    nitf_Reader_destruct(&reader);

    return 0;

CATCH_ERROR:
    if (input_io) nitf_IOHandle_close(input_io);
    if (output_io) nitf_IOHandle_close(output_io);
    if (record2) nitf_Record_destruct(&record2);
    if (reader) nitf_Reader_destruct(&reader);
    if (record) nitf_Record_destruct(&record);
    if (writer) nitf_Writer_destruct(&writer);
    nitf_Error_print(&error, stdout, "Exiting...");
    exit(EXIT_FAILURE);
}
Example #27
0
/**
 * Main program
 * @param  argc Number of command line arguments, inlucing the program itself.
 * @param  argv Vector of command line arguments.
 * @return      EXIT_SUCCESS if program exits normally, EXIT_ERROR otherwise.
 */
int main(int argc, char** argv) {
  if(argc < 2 || argc > 3) {
    std::cout << "Usage: warper input_image [ouput_image]" << std::endl;
    return EXIT_FAILURE;
  }

  readImage(argv[1]);

  Matrix3x3 M(1.0, 0.0, 0.0,
              0.0, 1.0, 0.0,
              0.0, 0.0, 1.0);
  process_input(M, originalWidth, originalHeight);

  Vector3d upperRight(originalWidth-1,originalHeight-1, 1);
  Vector3d lowerRight(originalWidth-1,0, 1);
  Vector3d upperLeft(0,originalHeight-1, 1);
  Vector3d lowerLeft(0,0, 1);

  upperRight = (M * upperRight)/upperRight[2];
  lowerRight = (M * lowerRight)/lowerRight[2];
  upperLeft = (M * upperLeft)/upperLeft[2];
  lowerLeft = (M * lowerLeft)/lowerLeft[2];

  newWidth = max(max(lowerLeft[0], lowerRight[0]), max(upperLeft[0], upperRight[0]));
  newHeight = max(max(lowerLeft[1], lowerRight[1]), max(upperLeft[1], upperRight[1]));

  int originX = min(min(lowerLeft[0], lowerRight[0]), min(upperLeft[0], upperRight[0]));
  int originY = min(min(lowerLeft[1], upperLeft[1]), min(lowerRight[1], upperRight[1]));

  newHeight = newHeight - originY;
  newWidth = newWidth - originX;

  Vector3d newOrigin(originX, originY, 0);

  // Initalize 2d array
  warppedPixels = new rgba_pixel*[newHeight];
  warppedPixels[0] = new rgba_pixel[newWidth*newHeight];

  for (int i=1; i < newHeight; i++) {
    warppedPixels[i] = warppedPixels[i-1] + newWidth;
  }

  Matrix3x3 invM = M.inv();

  for(int row = 0; row < newHeight; row++)
    for(int col = 0; col < newWidth; col++) {

      Vector3d pixel_out(col, row, 1);
      pixel_out = pixel_out + newOrigin;
      Vector3d pixel_in = invM * pixel_out;

      float u = pixel_in[0] / pixel_in[2];
      float v = pixel_in[1] / pixel_in[2];

      int roundedU = round(u);
      int roundedV = round(v);

      if((0 <= roundedU && roundedU < originalWidth) && (0 <= roundedV && roundedV < originalHeight)) {
          warppedPixels[row][col] = pixels[roundedV][roundedU];
        }
      else {
        rgba_pixel p;
        p.r = 0;
        p.g = 0;
        p.b = 0;
        p.a = 1;
        warppedPixels[row][col] = p;
      }
    }

    // Flip for openGL
    openGLFlip();

    // Init OpenGL
    glutInit(&argc, argv);
    openGLSetup(newWidth, newHeight);

    if(argc == 3) {
      outImage = argv[2];
      writeImage();
    }

    // Start running display window
    glutMainLoop();

  return EXIT_SUCCESS;
}
Example #28
0
int main(int argc, char *argv[])
{
	struct options opts;
	image_t* img;
	image_t* mask;

	parse_arguments(argc, argv, &opts);
	verbose_level = opts.verbose;

	img = readImage(opts.infile);
	if (!img)
		return EXIT_FAILURE;
	if (img->color_type != PNG_COLOR_TYPE_RGB)
	{
		verbose(1, "Input image must be RGB, 8 bits per channel (or fix the code)\n");
		freeImage(img);
		return EXIT_FAILURE;
	}
	if (!img->trans_values)
	{
		verbose(2, "%s has no tRNS chunk, assuming transparent black (RBG 0,0,0)\n",
				opts.infile);
		img->trans_values = &img->trans_values_buf;
	}
	img->num_trans = 0;

	mask = readImage(opts.maskfile);
	if (!mask)
	{
		freeImage(img);
		return EXIT_FAILURE;
	}
	if (mask->w < img->w || mask->h < img->h)
	{
		verbose(1, "Mask image dimensions are smaller than input image\n");
		freeImage(img);
		freeImage(mask);
		return EXIT_FAILURE;
	}
	else if (mask->w != img->w || mask->h != img->h)
		verbose(2, "Warning: input image and mask have different dimensions\n");

	if (mask->color_type != PNG_COLOR_TYPE_GRAY && mask->color_type != PNG_COLOR_TYPE_PALETTE)
	{
		verbose(1, "Mask image must be grayscale or paletted (or fix the code)\n");
		freeImage(img);
		freeImage(mask);
		return EXIT_FAILURE;
	}
	if (opts.alpha && (mask->color_type & PNG_COLOR_MASK_PALETTE))
	{
		verbose(2, "Warning: ignoring palette in mask image; using indices\n");
	}
	if (opts.alpha && mask->bit_depth != 8)
	{
		verbose(1, "Mask image for the alpha channel must be 8bpp\n");
		freeImage(img);
		freeImage(mask);
		return EXIT_FAILURE;
	}
	if (!opts.alpha && mask->trans)
	{
		mask->trans_index = getImageTransIndex(mask);
		verbose(2, "Using mask image transparency info; trans index %d\n", mask->trans_index);
	}
	else if (!opts.alpha)
	{
		mask->trans_index = 0;
		verbose(2, "Mask image has no transparency info; using index %d\n", mask->trans_index);
	}

	if (!opts.maskon && !opts.maskoff && !opts.alpha)
	{
		freeImage(img);
		freeImage(mask);
		verbose(1, "Nothing to do; specify -0 or -1, or use -a\n");
		return EXIT_SUCCESS;
	}

	if (opts.alpha && (opts.maskon || opts.maskoff))
	{
		verbose(2, "Options -0 and -1 have no effect when -a specified\n");
	}

	if (opts.alpha)
		alphaImage(img, mask);
	else
		maskImage(img, mask, opts.maskon, opts.maskoff);
	
	writeImage(img, opts.outfile);

	freeImage(img);
	freeImage(mask);

	return EXIT_SUCCESS;
}
Example #29
0
int main(int argc,char** argv)
{
  AnalyzeImage img,timg;
  int intstatus;
  int i,j,k;
  int xtrans,ytrans,ztrans,xstart,ystart,zstart,xend,yend,zend;
  bool status;

  if( argc < 6) {
    cout << "Usage: translate_analyze inputfile outputfile x_trans y_trans z_trans" << endl;
    cout << "Images are assumed to be transaxial." << endl;
    cout << "Translations are given relative to voxels and not in millimeters" << endl;   
  }
  intstatus = readImage(argv[1],&img);
  if(intstatus != 0) {
    cout << "Could not read the file" << argv[1] << endl;
    return(2);
  }
  xtrans = atoi(argv[3]);
  ytrans = atoi(argv[4]);
  ztrans = atoi(argv[5]);

  if(xtrans < 0) {
    xstart = -xtrans;
    xend = img.header.x_dim;
  }
  else {  
    xstart = 0;
    xend = img.header.x_dim - xtrans;
  }   
  if(ytrans < 0) {
    ystart = -ytrans;
    yend = img.header.y_dim;
  }
  else {  
    ystart = 0;
    yend = img.header.y_dim - ytrans;
  }   
  if(ztrans < 0) {
    zstart = -ztrans;
    zend = img.header.z_dim;
  }
  else {  
    zstart = 0;
    zend = img.header.z_dim - ztrans;
  }   
 
  status = newImage(&timg,&img);
  for(i = xstart;i < xend;i++) {  
    for(j = ystart;j < yend;j++) {
      for(k = zstart;k < zend;k++) {
        putVoxelValue(&timg,i + xtrans ,j + ytrans,k + ztrans,getVoxelValue(&img,i,j,k));
      }
    }
  }
  intstatus = writeImage(argv[2],&timg,true);
  if(intstatus != 0) {
    cout << "Could not write the file" << argv[2] << endl;
    return(3);
  }
  return(0);
}
Example #30
0
int main(int argc, char *argv[])
{
	int threshold, rh, theta, rows, cols, rScale, tScale, hitImage, i;
	char *inputo, *inputh, *inpute, *outputl;
	float r, t, diag, x, y, c, s;
	Image io, ih, ie;

	if (argc < 5) {
		fprintf(stderr, "usage: %s <input original scene image> <input hough image> <input thresholded image> <hough threshold> <cropped line-detected output image>\n", argv[0]);
		exit(0);
	}

	inputo = argv[1];
	inputh = argv[2];
	inpute = argv[3];
	if (sscanf(argv[4], "%d", &threshold) != 1) {
		fprintf(stderr, "error: threshold not an integer\n");
		exit(1);
	}
	outputl = argv[5];

	if (readImage(&io, inputo) == -1) {
		std::cerr << "Error reading file " << inputo << "\n";
		exit(1);
	} else if (readImage(&ih, inputh) == -1) {
		std::cerr << "Error reading file " << inputh << "\n";
		exit(1);
	} else if (readImage(&ie, inpute) == -1) {
		std::cerr << "Error reading file " << inpute << "\n";
		exit(1);
	}	
	rows = getNRows(&io);
	cols = getNCols(&io);
	diag = sqrt(pow(rows, 2) + pow(cols, 2));
	rScale = getNRows(&ih);
	tScale = getNCols(&ih);

	for (rh = 0; rh < rScale; ++rh) {
		for (theta = 0; theta < tScale; ++theta) {
			if (getPixel(&ih, rh, theta) >= threshold) {
				r = ((2*diag)/rScale)*rh - diag;
				t = (PI/tScale)*theta - PI/2;
				c = cos(t);
				s = sin(t);

				x = -r*s; // cos(t + pi/2) = -sin(t)
				y = r*c; // sin(t + pi/2) = cos(t)
				if (inImage(&io, x, y)) {
       			x -= diag*c;
					y -= diag*s;
				}

				hitImage = 0;
				i = 0;
				while (!hitImage || inImage(&io, x + i*c, y + i*s)) {
					if (!hitImage && inImage(&io, x + i*c, y + i*s))
						hitImage = 1;
					if (hitImage && getPixel(&ie, y + i*s, x + i*c)) {
						setPixel(&io, y + i*s, x + i*c, 255);
					}
					i++;
				}
			}
		}
	}

	setColors(&io, 255);
	if (writeImage(&io, outputl) == -1) {
		std::cerr << "Error writing file " << outputl << "\n";
	}
	free(io.data);
	free(ih.data);
	free(ie.data);
}