C Programming turning array into an image - c

I am using C to run a phase retrieval algorithm on images.
I am using ImageJ to convert the .png into a text image that I then read into my code and run the code.
At the end I have printed the output to a text array, and then have to read it from imageJ as a text image.
I was wondering if there is a way to get an image straight from c?

You could try to use OpenCv, an Open source library of programming functions for computer vision tasks.
It could read and write on diferent image file formats using imread and imwrite functions, as you could see on this example from OpenCv's documentation web site:
#include <cv.h>
#include <highgui.h>
using namespace cv;
int main( int argc, char** argv )
{
char* imageName = argv[1];
Mat image;
image = imread( imageName, 1 );
if( argc != 2 || !image.data )
{
printf( " No image data \n " );
return -1;
}
Mat gray_image;
cvtColor( image, gray_image, CV_BGR2GRAY );
imwrite( "../../images/Gray_Image.jpg", gray_image );
namedWindow( imageName, CV_WINDOW_AUTOSIZE );
namedWindow( "Gray image", CV_WINDOW_AUTOSIZE );
imshow( imageName, image );
imshow( "Gray image", gray_image );
waitKey(0);
return 0;
}
Hope it helps!

Related

unsigned char pixel_intensity[] to image; C code, Linux

I have a data array of pixel intensity (e.g. unsigned char pixel_intensity[4] = {0, 255, 255, 0}) and I need to create image in C code on Linux (Raspberry Pi).
What is the easiest way to do it?
I would suggest using the netpbm format as it is very easy to program. It is documented here and here.
I have written a little demonstration of how to write a simple greyscale ramp to a 100x256 image below.
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *imageFile;
int x,y,pixel,height=100,width=256;
imageFile=fopen("image.pgm","wb");
if(imageFile==NULL){
perror("ERROR: Cannot open output file");
exit(EXIT_FAILURE);
}
fprintf(imageFile,"P5\n"); // P5 filetype
fprintf(imageFile,"%d %d\n",width,height); // dimensions
fprintf(imageFile,"255\n"); // Max pixel
/* Now write a greyscale ramp */
for(x=0;x<height;x++){
for(y=0;y<width;y++){
pixel=y;
fputc(pixel,imageFile);
}
}
fclose(imageFile);
}
The header of the image looks like this:
P5
256 100
255
<binary data of pixels>
And the image looks like this (I have made it into a JPEG for rendering on here)
Once you have an image, you can use the superb ImageMagick (here) tools to convert the image to anything else you like, e.g. if you want the greyscale created by the above converted into a JPEG, just use ImageMagick like this:
convert image.pgm image.jpg
Or, if you want a PNG
convert image.pgm image.png
You can actually use the PGM format images directly on the web, by convention, the MIME type is image/x-portable-graymap

Colour conversion not working in opencv?

#include<highgui.h>
#include<cxcore.h>
#include<cv.h>
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[])
{
IplImage* img = cvLoadImage("hello.jpg", CV_WINDOW_FULLSCREEN );
int *img_data;
img_data = malloc(sizeof(*img_data)*img->height*img->width*img->nChannels);
if (!img)
{
printf("Image can NOT Load!!!\n");
return 1;
}
cvNamedWindow("myfirstwindow", CV_WINDOW_FREERATIO );
cvShowImage("myfirstwindow", img);
printf("Height: %d\nwidth: %d\nnchannels:%d\n",img->height,img->width,img->nChannels);
cvCvtColor(img,img_data,CV_RGB2XYZ);
cvWaitKey(0);
cvReleaseImage(&img);
return 0;
}
In this program I am trying to convert RGB color model to XYZ color model using function cvCvtColor. And i am getting error shown below:
OpenCV Error: Bad argument (Unknown array type) in cvarrToMat, file
/build/buildd/opencv-2.3.1/modules/core/src/matrix.cpp, line 646
terminate called after throwing an instance of 'cv::Exception'
what(): /build/buildd/opencv-2.3.1/modules/core/src/matrix.cpp:646:
error: (-5) Unknown array type in function cvarrToMat
Any help or suggestion will be greatly appreciated. Thank you.
do yourself (and us) a favour, and switch to the c++ api.
the old c-api is no longer developed, and only around for maintenance, don't write any new code in that !
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
using namespace cv;
int main()
{
namedWindow("myfirstwindow", CV_WINDOW_FREERATIO );
Mat img = imread("hello.jpg", CV_IMAGE_LOAD_COLOR);
imshow("myfirstwindow",img);
Mat hsv;
cvtColor(img,hsv,CV_RGB2HSV);
waitKey(0);
return 0;
}
You are passing enum value CV_WINDOW_FULLSCREEN which is meant for specifying the property of window when calling cvNamedWindow. For image loading, it should be some enum value like CV_LOAD_IMAGE_COLOR or CV_LOAD_IMAGE_GRAYSCALE.
But your code is not crashing here because fortunately, the integral value of CV_WINDOW_FULLSCREEN and CV_LOAD_IMAGE_COLOR is same, i.e. 1, so basically these enum values are equal.
The real cause of error in the code is you are passing raw int* to the function cvCvtColor. All opencv C functions expect IplImage* as arguments. The following line is causing the error.
cvCvtColor(img,img_data,CV_RGB2XYZ);
You might want to do something like this:
int main(int argc, char* argv[])
{
IplImage* img = cvLoadImage("hello.jpg", CV_LOAD_IMAGE_COLOR);
IplImage *img_data;
img_data = cvCreateImage(cvGetSize(img), img->depth, img->nChannels);
if (!img)
{
printf("Image can NOT Load!!!\n");
return 1;
}
cvNamedWindow("myfirstwindow", CV_WINDOW_FREERATIO );
cvShowImage("myfirstwindow", img);
printf("Height: %d\nwidth: %d\nnchannels:%d\n",img->height,img->width,img->nChannels);
cvCvtColor(img,img_data,CV_RGB2XYZ);
cvWaitKey(0);
cvReleaseImage(&img);
cvReleaseImage(&img_data);
return 0;
}
You need to pass CV_LOAD_IMAGE_COLOR to the function cvLoadImage(), which will load color image.

Cleaned up camera osx and opencv

hi guys i am executing some sample programs at my macbook using opencv and this is my code:
#include "stdio.h"
#include "cv.h"
#include "highgui.h"
int main( int argc, char **argv )
{
CvCapture *capture = 0;
IplImage *frame = 0;
int key = 0;
/* initialize camera */
capture = cvCaptureFromCAM( 0 );
/* always check */
if ( !capture ) {
fprintf( stderr, "Cannot open initialize webcam!\n" );
return 1;
}
/* create a window for the video */
cvNamedWindow( "result", CV_WINDOW_AUTOSIZE );
while(1>0)
{
/* get a frame */
frame = cvQueryFrame( capture );
/* always check */
if(!frame ) break;
/* display current frame */
cvShowImage( "result", frame );
waitKey(10);
/* exit if user press 'Esc' */
key = cvWaitKey( 20 );
if((char)key==27 )
break;
}
/* free memory */
cvReleaseCapture( &capture );
cvDestroyWindow( "result" );
return 0;
}
the code was working fine on the Macbookpro about a year ago ( OSX snow leopard ) but at the macbook (lion) i only get this at the console: Cleaned up camera. No isight, no image... nothing, only that message? any advise o.0?
ps? i changed the number at Caoture FromCAM to 300 ( iEEE cameras ) or 500 (quicktime ) then i have no message but still no image.
Never mind guys, apparently is an issue on the current opencv version 2.6.x. I unistalled ffmpeg brew uninstall ffmepg and opencv brew uninstall opencv
then i changed my opencv version cd /usr/local/Library/Taps/homebrew-science i searched other version ( isight was working under 4.5.5 ) brew versions opencv and i added the 2.4.5 git chekout ae74fe9 opencv.rb finally i installed opencv using brew install opencv and it is done isight works great :).
ps: isight camera will work with cvCaptureFromCAM( 500 ) not 0, -1 or 300.
ps2: omg i am so happy :3

Labwindows fails to compile- says it is missing a dll that is already in project

I'm trying to use openCV with LabWindows 2012SP1. I've got a simple project attempting to run a simple "Hello World" program in debug mode.
The code I'm trying to run is
#include <cv.h>
#include <highgui.h>
// Create a window to show the image
cvNamedWindow( "My Cool Window", CV_WINDOW_AUTOSIZE );
IplImage *img = cvCreateImage( cvSize( 300, 100 ), IPL_DEPTH_8U, 3 );
double hScale = 1.0;
double vScale = 1.0;
double shear = 0.0;
int lineWidth = 2;
// Initialize the font
CvFont font;
cvInitFont( &font, CV_FONT_HERSHEY_SCRIPT_COMPLEX, hScale, vScale, shear, lineWidth, 8 );
// Write on the image ...
CvScalar color = CV_RGB( 0, 51, 102 );
cvPutText( img, "Hello World!", cvPoint( 60, 60 ), &font, color );
// ... and show it to the world !
cvShowImage( "My Cool Window", img );
// Wait until the user wants to exit
cvWaitKey(0);
and I have the following libraries added:
opencv_core247d.lib (32-bit)
opencv_highgui247d.lib (32-bit)
opencv_imgproc247d.lib (32-bit)
opencv_imgproc247d.dll
However, when I go to run the program in debug mode, I get an error telling me:
The program can't start because opencv_imgproc247d.dll is missing
from your computer. Try reinstalling the program to fix this problem.
I'm more than a little bit confused at this point, as I have the DLL in question added to the project.
Help?
you need to add the location of the opencv dll's to the 'PATH' env var.
please don't use the old c-api (won't be supported in near future), ( IplImages, cv* functions ). use cv::Mat and the c++ api(namespace cv) instead.

read/write avi video on MAC using openCV

I am trying to read avi video and write it again as it is without any change using openCV 2.4.0 on MAC 10.6.8
My videos is grayscale with frame_rate = 25 and Codec = 827737670 which is FFV1 (I guess)
The problem is ....
when I read and write the video as it is .... I see many changes in size and in color ...
After 3 or 4 times of writing I can see the video start to be (Pink) color !!!
I am not sure what is the problem !!!
this is my code for the people who interest
Appreciate your help in advance :D
Seereen
Note : I have on my computer FFMPEG V 0.11 (I do not know if this important)
{
int main (int argc, char * const argv[]) {
char name[50];
if (argc==1)
{
printf("\nEnter the name of the video:");
scanf("%s",name);
} else if (argc == 2)
strcpy(name, argv[1]);
else
{
printf("To run this program you should enter the name of the program at least, or you can enter the name of the program then the file name");
return 0;
}
cvNamedWindow( "Read the video", CV_WINDOW_AUTOSIZE );
// GET video
CvCapture* capture = cvCreateFileCapture( name );
if (!capture )
{
printf( "Unable to read input video." );
return 0;
}
double fps = cvGetCaptureProperty( capture,CV_CAP_PROP_FPS);
printf( "fps %f ",fps );
int codec = cvGetCaptureProperty( capture,CV_CAP_PROP_FOURCC);
printf( "codec %d ",codec );
// Read frame
IplImage* frame = cvQueryFrame( capture );
// INIT the video writer
CvVideoWriter *writer = cvCreateVideoWriter( "x7.avi", codec, fps, cvGetSize(frame),1);
while(1)
{
cvWriteFrame( writer, frame );
cvShowImage( "Read the video", frame );
// READ next frame
frame = cvQueryFrame( capture );
if( !frame )
break;
char c = cvWaitKey(33);
if( c == 27 )
break;
}
// CLEAN everything
cvReleaseImage( &frame );
cvReleaseCapture( &capture );
cvReleaseVideoWriter( &writer );
cvDestroyWindow( "Read the video" );
return 0;}
}
Check this list of fourcc codes, and search for the uncompressed ones, like HFYU.
You also might find this article interesting: Truly lossless video recording with OpenCV.
EDIT:
I have a Mac OS X 10.7.5 at my disposal and since you gave us the video for testing I decided to share my findings.
I wrote the following source code for testing purposes: it loads your video file and writes it to a new file out.avi while preserving the codec information:
#include <cv.h>
#include <highgui.h>
#include <iostream>
int main(int argc, char* argv[])
{
// Load input video
cv::VideoCapture input_cap(argv[1]);
if (!input_cap.isOpened())
{
std::cout << "!!! Input video could not be opened" << std::endl;
return -1;
}
// Setup output video
cv::VideoWriter output_cap("out.avi",
input_cap.get(CV_CAP_PROP_FOURCC),
input_cap.get(CV_CAP_PROP_FPS),
cv::Size(input_cap.get(CV_CAP_PROP_FRAME_WIDTH), input_cap.get(CV_CAP_PROP_FRAME_HEIGHT)));
if (!output_cap.isOpened())
{
std::cout << "!!! Output video could not be opened" << std::endl;
return -1;
}
// Loop to read from input and write to output
cv::Mat frame;
while (true)
{
if (!input_cap.read(frame))
break;
output_cap.write(frame);
}
input_cap.release();
output_cap.release();
return 0;
}
The output video presented the same characteristics of the input:
Codec: FFMpeg Video 1 (FFV1)
Resolution: 720x480
Frame rate: 25
Decoded format: Planar 4:2:0 YUV
and it looked fine when playing.
I'm using OpenCV 2.4.3.
I figure out the problem ,,,,,
The original videos written in YUV240 pixel format (and it is gray)
the openCV read the video on BGR by default , so each time when I read it the openCV convert the pixel values to BGR
after few time of reading and writing , the error start to be bigger (because the conversion operation)
that why the pixels values change .....and I see the video pink !
The Solution is , read and write this kind of videos by FFMPEG project which provide YUV240 and many other format
there is a code can do this operation in the tutorial of FFMPEG
I hope this can help the others who face similar problem

Resources