jpeg.cpp 12.1 KB
Newer Older
André Anjos's avatar
André Anjos committed
1
2
3
4
/**
 * @file io/cxx/ImageJpegFile.cc
 * @date Wed Oct 10 16:38:00 2012 +0200
 * @author Laurent El Shafey <laurent.el-shafey@idiap.ch>
Manuel Günther's avatar
Manuel Günther committed
5
 * @author Manuel Gunther <siebenkopf@googlemail.com>
André Anjos's avatar
André Anjos committed
6
7
8
9
10
 *
 * @brief Implements an image format reader/writer using libjpeg.
 * This codec is only able to work with 3D input/output.
 *
 * Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland
Manuel Günther's avatar
Manuel Günther committed
11
 * Copyright (c) 2016, Regents of the University of Colorado on behalf of the University of Colorado Colorado Springs.
André Anjos's avatar
André Anjos committed
12
13
 */

14
15
#ifdef HAVE_LIBJPEG

André Anjos's avatar
André Anjos committed
16
17
18
19
20
21
22
23
24
#include <boost/filesystem.hpp>
#include <boost/shared_array.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <string>

25
#include <bob.core/logging.h>
26
#include <bob.io.image/jpeg.h>
27

André Anjos's avatar
André Anjos committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <jpeglib.h>

// Default JPEG quality
static int s_jpeg_quality = 92;

static boost::shared_ptr<std::FILE> make_cfile(const char *filename, const char *flags)
{
  std::FILE* fp = std::fopen(filename, flags);
  if(fp == 0) {
    boost::format m("the file `%s' could not be opened - verify permissions and availability");
    m % filename;
    throw std::runtime_error(m.str());
  }
  return boost::shared_ptr<std::FILE>(fp, std::fclose);
}


/**
 * ERROR HANDLING
 */
static void my_error_exit (j_common_ptr cinfo){
  // get error message
  char message[JMSG_LENGTH_MAX];
  cinfo->err->format_message(cinfo, message);
  // format error
53
54
  boost::format m("In image '%s' fatal JPEG error (%d) has occurred -> %s");
  m % reinterpret_cast<char*>(cinfo->client_data) % cinfo->err->msg_code % message;
André Anjos's avatar
André Anjos committed
55
56
57
58
59
60

  // Clean-up JPEG structures IS NOT required,
  // just raise the exception
  throw std::runtime_error(m.str());
}

61
62
63
64
65
66
static void my_output_message(j_common_ptr cinfo){
  // get warning message
  char message[JMSG_LENGTH_MAX];
  cinfo->err->format_message(cinfo, message);

  // log message as debug
67
  bob::core::debug << "In image '" << reinterpret_cast<char*>(cinfo->client_data) << "' JPEG warning has occured -> " << message << std::endl;
68
69
}

André Anjos's avatar
André Anjos committed
70
71
72
73

/**
 * LOADING
 */
74
static void im_peek(const std::string& path, bob::io::base::array::typeinfo& info) {
André Anjos's avatar
André Anjos committed
75
76
77
78
79
  // 1. JPEG structures
  struct jpeg_decompress_struct cinfo;
  struct jpeg_error_mgr jerr;
  cinfo.err = jpeg_std_error(&jerr);
  jerr.error_exit = my_error_exit;
80
81
82
  jerr.output_message = my_output_message;
  // set image name as client data; used for warning and error messages
  cinfo.client_data = const_cast<char*>(path.c_str());
André Anjos's avatar
André Anjos committed
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
  jpeg_create_decompress(&cinfo);

  // 2. JPEG file opening
  boost::shared_ptr<std::FILE> in_file = make_cfile(path.c_str(), "rb");
  jpeg_stdio_src(&cinfo, in_file.get());

  // 3. Read header
  jpeg_read_header(&cinfo, TRUE);

  // 4. Set parameters for decompression if any

  // 5. Start decompression and get information
  jpeg_start_decompress(&cinfo);

  if( cinfo.output_components != 1 && cinfo.output_components != 3)
  {
99
100
101
    // 6. clean up
    jpeg_destroy_decompress(&cinfo);

André Anjos's avatar
André Anjos committed
102
103
104
105
106
107
    boost::format m("unsupported number of planes (%d) when reading file. Image depth must be 1 or 3.");
    m % cinfo.output_components;
    throw std::runtime_error(m.str());
  }

  // Set depth and number of dimensions
108
  info.dtype = bob::io::base::array::t_uint8;
André Anjos's avatar
André Anjos committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
  info.nd = (cinfo.output_components == 1? 2 : 3);
  if(info.nd == 2)
  {
    info.shape[0] = cinfo.output_height;
    info.shape[1] = cinfo.output_width;
  }
  else
  {
    info.shape[0] = 3;
    info.shape[1] = cinfo.output_height;
    info.shape[2] = cinfo.output_width;
  }
  info.update_strides();

123
124
  // 6. clean up
  jpeg_destroy_decompress(&cinfo);
André Anjos's avatar
André Anjos committed
125
126
127
}

template <typename T> static
128
129
void im_load_gray(struct jpeg_decompress_struct *cinfo, bob::io::base::array::interface& b) {
  const bob::io::base::array::typeinfo& info = b.type();
André Anjos's avatar
André Anjos committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150

  T *element = static_cast<T*>(b.ptr());
  const int row_stride = info.shape[1];
  JSAMPROW buffer_pptr[1];
  while (cinfo->output_scanline < cinfo->image_height) {
    buffer_pptr[0] = element;
    jpeg_read_scanlines(cinfo, buffer_pptr, 1);
    element += row_stride;
  }
}

template <typename T> static
void imbuffer_to_rgb(size_t size, const T* im, T* r, T* g, T* b) {
  for (size_t k=0; k<size; ++k) {
    r[k] = im[3*k];
    g[k] = im[3*k +1];
    b[k] = im[3*k +2];
  }
}

template <typename T> static
151
152
void im_load_color(struct jpeg_decompress_struct *cinfo, bob::io::base::array::interface& b) {
  const bob::io::base::array::typeinfo& info = b.type();
André Anjos's avatar
André Anjos committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171

  long unsigned int frame_size = info.shape[1] * info.shape[2];
  T *element_r = static_cast<T*>(b.ptr());
  T *element_g = element_r+frame_size;
  T *element_b = element_g+frame_size;

  const int row_stride = cinfo->output_width * cinfo->output_components;
  JSAMPROW buffer_pptr[1];
  boost::shared_array<JSAMPLE> buffer(new JSAMPLE[row_stride]);
  buffer_pptr[0] = buffer.get();
  while (cinfo->output_scanline < cinfo->output_height) {
    jpeg_read_scanlines(cinfo, buffer_pptr, 1);
    imbuffer_to_rgb<T>(info.shape[2], reinterpret_cast<T*>(buffer_pptr[0]), element_r, element_g, element_b);
    element_r += cinfo->output_width;
    element_g += cinfo->output_width;
    element_b += cinfo->output_width;
  }
}

172
static void im_load(const std::string& filename, bob::io::base::array::interface& b) {
André Anjos's avatar
André Anjos committed
173
174
175
176
177
  // 1. JPEG structures
  struct jpeg_decompress_struct cinfo;
  struct jpeg_error_mgr jerr;
  cinfo.err = jpeg_std_error(&jerr);
  jerr.error_exit = my_error_exit;
178
179
180
  jerr.output_message = my_output_message;
  // set image name as client data; used for warning and error messages
  cinfo.client_data = const_cast<char*>(filename.c_str());
André Anjos's avatar
André Anjos committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
  jpeg_create_decompress(&cinfo);

  // 2. JPEG file opening
  boost::shared_ptr<std::FILE> in_file = make_cfile(filename.c_str(), "rb");
  jpeg_stdio_src(&cinfo, in_file.get());

  // 3. Read header
  jpeg_read_header(&cinfo, TRUE);

  // 4. Set parameters for decompression

  // 5. Start decompression and get information
  jpeg_start_decompress(&cinfo);

  // 6. Read content
196
197
  const bob::io::base::array::typeinfo& info = b.type();
  if(info.dtype == bob::io::base::array::t_uint8) {
André Anjos's avatar
André Anjos committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
    if(info.nd == 2) im_load_gray<uint8_t>(&cinfo, b);
    else if( info.nd == 3) im_load_color<uint8_t>(&cinfo, b);
    else {
      boost::format m("the image in file `%s' has a number of dimensions this jpeg codec has no support for: %s");
      m % filename % info.str();
      throw std::runtime_error(m.str());
    }
  }
  else {
    boost::format m("the image in file `%s' has a data type this jpeg codec has no support for: %s");
    m % filename % info.str();
    throw std::runtime_error(m.str());
  }

  // 7. Finish decompression
  jpeg_finish_decompress(&cinfo);

  // 8. Release JPEG decompression object
  jpeg_destroy_decompress(&cinfo);
}

/**
 * SAVING
 */
template <typename T>
223
224
static void im_save_gray(const bob::io::base::array::interface& b, struct jpeg_compress_struct *cinfo) {
  const bob::io::base::array::typeinfo& info = b.type();
André Anjos's avatar
André Anjos committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247

  const T* element = static_cast<const T*>(b.ptr());

  // pointer to a single row  (JSAMPLE is a typedef to unsigned char or char)
  JSAMPROW row_pointer[1];
  int row_stride = info.shape[1]; // JSAMPLEs per row in image_buffer
  while(cinfo->next_scanline < cinfo->image_height) {
    row_pointer[0] = const_cast<T*>(element);
    jpeg_write_scanlines(cinfo, row_pointer, 1);
    element += row_stride;
  }
}

template <typename T> static
void rgb_to_imbuffer(size_t size, const T* r, const T* g, const T* b, T* im) {
  for (size_t k=0; k<size; ++k) {
    im[3*k]   = r[k];
    im[3*k+1] = g[k];
    im[3*k+2] = b[k];
  }
}

template <typename T>
248
249
static void im_save_color(const bob::io::base::array::interface& b, struct jpeg_compress_struct *cinfo) {
  const bob::io::base::array::typeinfo& info = b.type();
André Anjos's avatar
André Anjos committed
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270

  long unsigned int frame_size = info.shape[1] * info.shape[2];

  const T *element_r = static_cast<const T*>(b.ptr());
  const T *element_g = element_r + frame_size;
  const T *element_b = element_g + frame_size;

  // pointer to a single row  (JSAMPLE is a typedef to unsigned char or char)
  boost::shared_array<JSAMPLE> row(new JSAMPLE[3*info.shape[2]]);
  JSAMPROW array_ptr[1];
  array_ptr[0] = row.get();
  int row_color_stride = info.shape[2]; // JSAMPLEs per row in image_buffer
  while(cinfo->next_scanline < cinfo->image_height) {
    rgb_to_imbuffer(row_color_stride, element_r, element_g, element_b, reinterpret_cast<T*>(array_ptr[0]));
    jpeg_write_scanlines(cinfo, array_ptr, 1);
    element_r += row_color_stride;
    element_g += row_color_stride;
    element_b += row_color_stride;
  }
}

271
272
static void im_save (const std::string& filename, const bob::io::base::array::interface& array) {
  const bob::io::base::array::typeinfo& info = array.type();
André Anjos's avatar
André Anjos committed
273
274
275
276
277
278

  // 1. JPEG structures
  struct jpeg_compress_struct cinfo;
  struct jpeg_error_mgr jerr;
  cinfo.err = jpeg_std_error(&jerr);
  jerr.error_exit = my_error_exit;
279
280
281
  jerr.output_message = my_output_message;
  // set image name as client data; used for warning and error messages
  cinfo.client_data = const_cast<char*>(filename.c_str());
André Anjos's avatar
André Anjos committed
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
  jpeg_create_compress(&cinfo);

  // 2. JPEG opening
  boost::shared_ptr<std::FILE> out_file = make_cfile(filename.c_str(), "wb");
  jpeg_stdio_dest(&cinfo, out_file.get());

  // 3. Set compression parameters
  cinfo.image_height = (info.nd == 2 ? info.shape[0] : info.shape[1]);
  cinfo.image_width = (info.nd == 2 ? info.shape[1] : info.shape[2]);
  cinfo.input_components = (info.nd == 2 ? 1 : 3);
  cinfo.in_color_space = (info.nd == 2 ? JCS_GRAYSCALE : JCS_RGB); // colorspace of input image
  jpeg_set_defaults(&cinfo);
  jpeg_set_quality(&cinfo, s_jpeg_quality, TRUE);

  // 4.
Amir Mohammadi's avatar
Amir Mohammadi committed
297
  jpeg_start_compress(&cinfo, TRUE);
André Anjos's avatar
André Anjos committed
298
299

  // Writes content
300
  if(info.dtype == bob::io::base::array::t_uint8) {
André Anjos's avatar
André Anjos committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326

    if(info.nd == 2) im_save_gray<uint8_t>(array, &cinfo);
    else if(info.nd == 3) {
      if(info.shape[0] != 3) throw std::runtime_error("color image does not have 3 planes on 1st. dimension");
      im_save_color<uint8_t>(array, &cinfo);
    }
    else {
      boost::format m("the image array to be written at file `%s' has a number of dimensions this jpeg codec has no support for: %s");
      m % filename % info.str();
      throw std::runtime_error(m.str());
    }
  }
  else {
    boost::format m("the image array to be written at file `%s' has a data type this jpeg codec has no support for: %s");
    m % filename % info.str();
    throw std::runtime_error(m.str());
  }

  // 6.
  jpeg_finish_compress(&cinfo);

  // 7.
  jpeg_destroy_compress(&cinfo);
}


327
328
329
/**
 * JPEG class
*/
André Anjos's avatar
André Anjos committed
330

331
332
333
334
335
336
337
338
339
340
bob::io::image::JPEGFile::JPEGFile(const char* path, char mode)
: m_filename(path),
  m_newfile(true)
{
  //checks if file exists
  if (mode == 'r' && !boost::filesystem::exists(path)) {
    boost::format m("file '%s' is not readable");
    m % path;
    throw std::runtime_error(m.str());
  }
André Anjos's avatar
André Anjos committed
341

342
  if (mode == 'r' || (mode == 'a' && boost::filesystem::exists(path))) {
Manuel Günther's avatar
Manuel Günther committed
343
344
345
346
    im_peek(path, m_type);
    m_length = 1;
    m_newfile = false;
  } else {
347
348
349
350
    m_length = 0;
    m_newfile = true;
  }
}
André Anjos's avatar
André Anjos committed
351
352


353
354
355
void bob::io::image::JPEGFile::read(bob::io::base::array::interface& buffer, size_t index) {
  if (m_newfile)
    throw std::runtime_error("uninitialized image file cannot be read");
André Anjos's avatar
André Anjos committed
356

357
  if (!buffer.type().is_compatible(m_type)) buffer.set(m_type);
André Anjos's avatar
André Anjos committed
358

359
360
  if (index != 0)
    throw std::runtime_error("cannot read image with index > 0 -- there is only one image in an image file");
André Anjos's avatar
André Anjos committed
361

362
  if(!buffer.type().is_compatible(m_type)) buffer.set(m_type);
André Anjos's avatar
André Anjos committed
363

364
365
366
  // load jpeg
  im_load(m_filename, buffer);
}
André Anjos's avatar
André Anjos committed
367

368
369
370
371
372
373
374
375
size_t bob::io::image::JPEGFile::append(const bob::io::base::array::interface& buffer) {
  if (m_newfile) {
    im_save(m_filename, buffer);
    m_type = buffer.type();
    m_newfile = false;
    m_length = 1;
    return 0;
  }
André Anjos's avatar
André Anjos committed
376

377
378
  throw std::runtime_error("image files only accept a single array");
}
André Anjos's avatar
André Anjos committed
379

380
381
382
383
384
385
void bob::io::image::JPEGFile::write(const bob::io::base::array::interface& buffer) {
  //overwriting position 0 should always work
  if (m_newfile) {
    append(buffer);
    return;
  }
André Anjos's avatar
André Anjos committed
386

387
388
  throw std::runtime_error("image files only accept a single array");
}
André Anjos's avatar
André Anjos committed
389
390
391



392
std::string bob::io::image::JPEGFile::s_codecname = "bob.image_jpeg";
André Anjos's avatar
André Anjos committed
393

394
boost::shared_ptr<bob::io::base::File> make_jpeg_file (const char* path, char mode) {
395
  return boost::make_shared<bob::io::image::JPEGFile>(path, mode);
396
397
398
}

#endif // HAVE_LIBJPEG