Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open an image using C?

Tags:

c

I have opened a .txt file many times using the C language's file handling facilities. But when I try to open an image file using the same procedure as for text files, I just can't do that. I even tried this by opening the image file in binary mode "rb".

This is the code I'm using:

#include "file.h"
#include "stdio.h"

main()
{
    FILE *fp;
    char ch;
    fp = fopen("D:\\setups\\tcc\\Bluehills.bmp", "rb+");

    if(fp == NULL)
    {
        printf("Error in opening the image");
        fclose(fp);
        exit(0);
    }

    printf("Successfully opened the image file");

    while((ch = fgetc(fp)) != EOF)
    {
        printf("%c", ch);
    }

    printf("\nWriting to o/p completed");
}

What do I need to modify to get the image as it is? As I'm directing the image output to the DOS window at least a monochrome pixel image must come up.

like image 945
SrinR Avatar asked Oct 23 '25 14:10

SrinR


1 Answers

The Opencv community offers some routines to load image, access the values of the image. In fact, in most of the opencv tutorial docs, we'll find a C version for many functions. You can look up this link C_Api functions.

However, there is one disclaimer: C routines of opencv are fewer compared to the C++/python routines. But if you have no choice, they are always there to fall back on.

Moreover, the Internet community believes that using C(Opencv routines) purposes is rather an outdated method for two reasons:

  1. The available routines are few in number(I have faced this problem).

  2. There is no compatibility between Mat objects of C++ and IplImage/cvMat objects of C.

    Some sample code(blurring) after including stdio.h, highgui.h, cv.h libraries:

int main( int argc, char** argv ) {
 
    IplImage* img = 0;
    IplImage* out = 0;

    if( argc < 2 ) {
        printf( "Usage: Accepts one image as argument\n" );
        exit( EXIT_SUCCESS );
    }

    img = cvLoadImage( argv[1] );

    if( !img ) {
        printf( "Error loading image file %s\n", argv[1]);
        exit( EXIT_SUCCESS );
    }

    out = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 3 );


    cvSmooth( img, out, CV_GAUSSIAN, 3, 3 );

    cvReleaseImage( &img );
    cvReleaseImage( &out );
    cvDestroyWindow( "Example1" );
    cvDestroyWindow( "Output" );
    return EXIT_SUCCESS;
}
like image 200
Eswar Avatar answered Oct 27 '25 01:10

Eswar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!