pnm.cpp
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024 #include <fvutils/readers/pnm.h>
00025 #include <fvutils/color/colorspaces.h>
00026 #include <fvutils/color/conversions.h>
00027 #include <core/exception.h>
00028
00029 #include <cstdlib>
00030 #include <cstring>
00031
00032 using namespace fawkes;
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043 PNMReader::PNMReader(const char* filename)
00044 {
00045 m_filename = strdup(filename);
00046 m_pnmfile = fopen(m_filename, "rb");
00047
00048 if ( m_pnmfile == NULL )
00049 {
00050 throw Exception("PNMReader::ctor: cannot open PNM file");
00051 }
00052
00053
00054 char* line = (char*) malloc(80);
00055
00056
00057 fgets(line, 80, m_pnmfile);
00058
00059 if ( strcmp("P6", line) > 0 )
00060 {
00061 throw Exception("PNMReader::ctor: unknown magic value");
00062 }
00063
00064
00065 do
00066 {
00067 fgets(line, 80, m_pnmfile);
00068 }
00069 while ( strncmp("#", line, 1) == 0);
00070
00071
00072 char* tmp = (char*) malloc(10);
00073 char* token;
00074 token = strtok(line, " ");
00075 if ( atoi(token) >= 0 ) { m_img_width = (unsigned int) atoi(token); }
00076 else { throw Exception("PNMReader::ctor: could not read out image width"); };
00077 token = strtok(NULL, " ");
00078 if ( atoi(token) >= 0 ) { m_img_height = (unsigned int) atoi(token); }
00079 else { throw Exception("PNMReader::ctor: could not read out image height"); };
00080 free(tmp);
00081
00082
00083 fgets(line, 80, m_pnmfile);
00084 int max = atoi(line);
00085 free(line);
00086 if ( max >= 0)
00087 {
00088 switch(max)
00089 {
00090 case 1:
00091 m_img_depth = 1;
00092 break;
00093
00094 case 15:
00095 m_img_depth = 2;
00096 break;
00097
00098 case 255:
00099 m_img_depth = 3;
00100 break;
00101
00102 default:
00103 break;
00104 }
00105 }
00106 else
00107 {
00108 throw Exception("PNMReader::ctor: unknown color depth");
00109 }
00110
00111 size_t img_size = m_img_width * m_img_height * m_img_depth;
00112 m_pnm_buffer = (unsigned char*) malloc(img_size);
00113 }
00114
00115
00116 PNMReader::~PNMReader()
00117 {
00118 free(m_filename);
00119 free(m_pnm_buffer);
00120 }
00121
00122 void
00123 PNMReader::set_buffer(unsigned char* buffer)
00124 {
00125 m_yuv_buffer = buffer;
00126 }
00127
00128 colorspace_t
00129 PNMReader::colorspace()
00130 {
00131 return YUV422_PLANAR;
00132 }
00133
00134 unsigned int
00135 PNMReader::pixel_width()
00136 {
00137 return m_img_width;
00138 }
00139
00140 unsigned int
00141 PNMReader::pixel_height()
00142 {
00143 return m_img_height;
00144 }
00145
00146 void
00147 PNMReader::read()
00148 {
00149 if (m_yuv_buffer == NULL)
00150 {
00151 throw Exception("PNMReader::read: buffer = NULL");
00152 }
00153
00154 fread(m_pnm_buffer, m_img_depth, m_img_width * m_img_height, m_pnmfile);
00155 convert(RGB, YUV422_PLANAR, m_pnm_buffer, m_yuv_buffer, m_img_width, m_img_height);
00156 }