1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 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 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
|
/*
* Copyright (c) 2009 Samit Basu
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <QImage>
#include <QImageWriter>
#include "Array.hpp"
#include "Algorithms.hpp"
#include <QtGui>
#include "PathSearch.hpp"
#include "Interpreter.hpp"
#include "Math.hpp"
//!
//@Module IMREAD Read Image File To Matrix
//@@Section IO
//@@Usage
//Reads the image data from the given file into a matrix. Note that
//FreeMat's support for @|imread| is not complete. Only some of the
//formats specified in the MATLAB API are implemented. The syntax
//for its use is
//@[
// [A,map,alpha] = imread(filename)
//@]
//where @|filename| is the name of the file to read from. The returned
//arrays @|A| contain the image data, @|map| contains the colormap information
//(for indexed images), and @|alpha| contains the alphamap (transparency).
//The returned values will depend on the type of the original image. Generally
//you can read images in the @|jpg,png,xpm,ppm| and some other formats.
//@@Signature
//sgfunction imread ImReadFunction
//inputs filename
//outputs A map alpha
//!
static ArrayVector imreadHelperIndexed(QImage img) {
QVector<QRgb> colorTable(img.colorTable());
int numcol = colorTable.size();
BasicArray<double> ctable_dp(NTuple(numcol,3));
for (int i=0;i<numcol;i++) {
QColor c(colorTable[i]);
ctable_dp[i+1] = (double) c.redF();
ctable_dp[i+numcol+1] = (double) c.greenF();
ctable_dp[i+2*numcol+1] = (double) c.blueF();
}
Array ctable(ctable_dp);
BasicArray<uint8> img_data_dp(NTuple(img.height(),img.width()));
for (int row=0;row<img.height();row++) {
uchar *p = img.scanLine(row);
for (int col=0;col<img.width();col++)
img_data_dp[row+col*img.height()+1] = p[col];
}
Array A(img_data_dp);
QImage alpha(img.alphaChannel());
BasicArray<uint8> img_alpha_dp(NTuple(img.height(),img.width()));
for (int row=0;row<alpha.height();row++) {
uchar *p = alpha.scanLine(row);
for (int col=0;col<alpha.width();col++)
img_alpha_dp[row+col*img.height()+1] = p[col];
}
Array trans(img_alpha_dp);
return ArrayVector() << A << ctable << trans;
}
static ArrayVector imreadHelperRGB32(QImage img) {
if (img.allGray()) {
BasicArray<uint8> img_data_dp(NTuple(img.height(),img.width()));
for (int row=0;row<img.height();row++) {
QRgb *p = (QRgb*) img.scanLine(row);
for (int col=0;col<img.width();col++) {
int ndx = row+col*img.height();
img_data_dp[ndx+1] = qGray(p[col]);
}
}
return ArrayVector() << Array(img_data_dp)
<< EmptyConstructor()
<< EmptyConstructor();
}
else {
BasicArray<uint8> img_data_dp(NTuple(img.height(),img.width(),3));
int imgcnt = img.height()*img.width();
for (int row=0;row<img.height();row++) {
QRgb *p = (QRgb*) img.scanLine(row);
for (int col=0;col<img.width();col++) {
int ndx = row+col*img.height();
img_data_dp[ndx+1] = qRed(p[col]);
img_data_dp[ndx+1*imgcnt+1] = qGreen(p[col]);
img_data_dp[ndx+2*imgcnt+1] = qBlue(p[col]);
}
}
return ArrayVector() << Array(img_data_dp)
<< EmptyConstructor()
<< EmptyConstructor();
}
}
static ArrayVector imreadHelperARGB32(QImage img) {
BasicArray<uint8> img_alpha_dp(NTuple(img.height(),img.width()));
if (img.allGray()) {
BasicArray<uint8> img_data_dp(NTuple(img.height(),img.width()));
for (int row=0;row<img.height();row++) {
QRgb *p = (QRgb*) img.scanLine(row);
for (int col=0;col<img.width();col++) {
int ndx = row+col*img.height();
img_data_dp[ndx+1] = qGray(p[col]);
img_alpha_dp[ndx+1] = qAlpha(p[col]);
}
}
return ArrayVector() << Array(img_data_dp)
<< EmptyConstructor()
<< Array(img_alpha_dp);
} else {
BasicArray<uint8> img_data_dp(NTuple(img.height(),img.width(),3));
int imgcnt = img.height()*img.width();
for (int row=0;row<img.height();row++) {
QRgb *p = (QRgb*) img.scanLine(row);
for (int col=0;col<img.width();col++) {
int ndx = row+col*img.height();
img_data_dp[ndx+1] = qRed(p[col]);
img_data_dp[ndx+1*imgcnt+1] = qGreen(p[col]);
img_data_dp[ndx+2*imgcnt+1] = qBlue(p[col]);
img_alpha_dp[ndx+1] = qAlpha(p[col]);
}
}
return ArrayVector() << Array(img_data_dp)
<< EmptyConstructor()
<< Array(img_alpha_dp);
}
}
ArrayVector ImReadFunction(int nargout, const ArrayVector& arg,
Interpreter* eval) {
PathSearcher psearch(eval->getTotalPath());
if (arg.size() == 0)
throw Exception("imread requires a filename to read.");
QString filename(arg[0].asString());
QString completename;
completename = psearch.ResolvePath(filename);
if( completename.isNull() )
throw Exception("unable to find file " + completename);
// Construct the QImage object
QImage img(completename);
if (img.isNull())
throw Exception("unable to read file " + completename);
if (img.format() == QImage::Format_Invalid)
throw Exception("file " + completename + " is invalid");
if (img.format() == QImage::Format_Indexed8) return imreadHelperIndexed(img);
if (img.format() == QImage::Format_RGB32) return imreadHelperRGB32(img);
if (img.format() == QImage::Format_ARGB32) return imreadHelperARGB32(img);
throw Exception("unsupported image format - only 8 bit indexed and 24 bit RGB and 32 bit ARGB images are supported");
return ArrayVector();
}
//!
//@Module IMWRITE Write Matrix to Image File
//@@Section IO
//@@Usage
//Write the image data from the matrix into a given file. Note that
//FreeMat's support for @|imwrite| is not complete.
//You can write images in the @|jpg,png,xpm,ppm| and some other formats.
//The syntax for its use is
//@[
// imwrite(A, filename)
// imwrite(A, map, filename)
// imwrite(A, map, filename, 'Alpha', alpha)
//
//or Octave-style syntax:
// imwrite(filename, A)
// imwrite(filename, A, map)
// imwrite(filename, A, map, alpha)
//@]
//where @|filename| is the name of the file to write to. The input array
//@|A| contains the image data (2D for gray or indexed, and 3D for color).
//If @|A| is an integer array (int8, uint8, int16, uint16, int32, uint32),
//the values of its elements should be within 0-255. If @|A| is a
//floating-point array (float or double), the value of its elements should
//be in the range [0,1]. @|map| contains the colormap information
//(for indexed images), and @|alpha| the alphamap (transparency).
//@@Example
//Here is a simple example of @|imread|/@|imwrite|. First, we generate
//a grayscale image and save it to an image file.
//@<
//a = uint8(255*rand(64));
//figure(1), image(a), colormap(gray)
//title('image to save')
//imwrite(a, 'test.bmp')
//@>
//Then, we read image file and show it:
//@<
//b = imread('test.bmp');
//figure(2), image(b), colormap(gray)
//title('loaded image')
//@>
//@@Tests
//@{ test_imwrite_imread.m
//% Test the imwrite and imread capability with random grayscale image
//function test_val = test_imwrite_imread
// a = uint8(255*rand(64));
// imwrite(a, 'test.bmp')
// b = imread('test.bmp');
// test_val = issame(a,b);
//@}
//@@Signature
//sgfunction imwrite ImWriteFunction
//inputs filename A map alpha
//outputs none
//!
static QImage imwriteHelperIndexed(Array A, Array ctable, Array trans) {
QImage img(int(A.columns()), int(A.rows()), QImage::Format_Indexed8);
uint8 *img_data_dp = A.real<uint8>().data();
uint8 *ctable_dp = ctable.real<uint8>().data();
uint8 *img_alpha_dp = trans.real<uint8>().data();
for (int row=0;row<img.height();row++) {
uchar *p = img.scanLine(row);
for (int col=0;col<img.width();col++)
p[col] = img_data_dp[row+col*img.height()];
}
if (ctable_dp) {
QVector<QRgb> colorTable(int(ctable.length()/3));
int numcol = colorTable.size();
for (int i=0;i<numcol;i++)
colorTable[i] = qRgb(int(ctable_dp[i]),
int(ctable_dp[i+numcol]),
int(ctable_dp[i+2*numcol]));
img.setColorTable(colorTable);
}
else {
int numrow = 256;
QVector<QRgb> colorTable(numrow);
for (int i=0;i<numrow;i++)
colorTable[i] = qRgb(i, i, i);
img.setColorTable(colorTable);
}
if (img_alpha_dp) {
QImage alpha(int(A.columns()), int(A.rows()), QImage::Format_Indexed8);
for (int row=0;row<alpha.height();row++) {
uchar *p = alpha.scanLine(row);
for (int col=0;col<alpha.width();col++)
p[col] = img_alpha_dp[row+col*img.height()];
}
img.setAlphaChannel(alpha);
}
return img;
}
static QImage imwriteHelperRGB32(Array A) {
uint8 *img_data_dp = A.real<uint8>().data();
QImage img(int(A.columns()), int(A.rows()), QImage::Format_RGB32);
int imgcnt = img.height()*img.width();
for (int row=0;row<img.height();row++) {
QRgb *p = (QRgb*) img.scanLine(row);
for (int col=0;col<img.width();col++) {
int ndx = row+col*img.height();
p[col] = qRgb(img_data_dp[ndx],
img_data_dp[ndx+1*imgcnt],
img_data_dp[ndx+2*imgcnt]);
}
}
return img;
}
static QImage imwriteHelperARGB32(Array A, Array trans) {
QImage img(int(A.columns()), int(A.rows()), QImage::Format_ARGB32);
uint8 *img_data_dp = A.real<uint8>().data();
uint8 *img_alpha_dp = trans.real<uint8>().data();
int imgcnt = img.height()*img.width();
for (int row=0;row<img.height();row++) {
QRgb *p = (QRgb*) img.scanLine(row);
for (int col=0;col<img.width();col++) {
int ndx = row+col*img.height();
p[col] = qRgba(img_data_dp[ndx],
img_data_dp[ndx+1*imgcnt],
img_data_dp[ndx+2*imgcnt],
img_alpha_dp[ndx]);
}
}
return img;
}
static Array convert2uint8(Array A) {
if (A.dataClass() == UInt8) return A;
if (A.dataClass() == Bool) A = A.toClass(Double);
if ((A.dataClass() == Float) || (A.dataClass() == Double))
return DotMultiply(A,Array(double(255.0))).toClass(UInt8);
return A.toClass(UInt8);
}
ArrayVector ImWriteFunction(int nargout, const ArrayVector& arg, Interpreter* eval) {
PathSearcher psearch(eval->getTotalPath());
if (arg.size() < 2)
throw Exception("imwrite requires at least a filename and a matrix");
ArrayVector argCopy;
if (arg[0].isString())
argCopy = arg; //Octave-style syntax
else if (arg[1].isString()) {
argCopy << arg[1];
for (int i = 0; i< arg.size()-1; i++){
if (i == 1)
continue;
argCopy << arg[i];
}
}
else if (arg[2].isString()) {
argCopy << arg[2];
for (int i = 0; i< arg.size()-1; i++){
if (i == 2)
continue;
argCopy << arg[i];
}
}
else
throw Exception("imwrite requires a filename");
int hasAlpha = 0;
for (int i = 1; i< arg.size(); i++) {
if (argCopy[i].isString() && argCopy[0].asString().toUpper() == "ALPHA") {
hasAlpha = 1;
break;
}
i++;
}
QString FileName = argCopy[0].asString();
QByteArray ImageFormat;
ImageFormat.append(QFileInfo(FileName).suffix());
// Construct the QImageWriter object
QImageWriter imgWriter(FileName,ImageFormat);
if (!imgWriter.canWrite()) {
throw Exception("unable to write image file " + FileName);
}
Array A(argCopy[1]);
if (A.dimensions().lastNotOne() == 2) { // choose QImage::Format_Indexed8
if (argCopy.size() == 2) { // 8-bit grayscale image
Array ctable(UInt8);
Array trans(UInt8);
QImage img = imwriteHelperIndexed(convert2uint8(A), ctable, trans);
if (!imgWriter.write(QImage(img)))
throw Exception("cannot create image file" + FileName);
}
else if (argCopy.size() == 3) { // 8-bit indexed color image
Array ctable(argCopy[2]);
if (ctable.length() != 0 && ctable.cols() != 3)
throw Exception("color map should be a 3 columns matrix");
Array trans(UInt8);
QImage img = imwriteHelperIndexed(convert2uint8(A), convert2uint8(ctable), trans);
if (!imgWriter.write(img))
throw Exception("cannot create image file" + FileName);
}
else if (argCopy.size() == 4) { // 8-bit indexed color image with alpha channel
Array ctable(argCopy[2]);
if (ctable.length() != 0 && ctable.cols() != 3)
throw Exception("color map should be a 3 columns matrix");
Array trans(argCopy[3]);
eval->warningMessage("saving alpha/transparent channel will increase file size");
QImage img = imwriteHelperIndexed(convert2uint8(A), convert2uint8(ctable), convert2uint8(trans));
if (!imgWriter.write(img))
throw Exception("cannot create image file" + FileName);
}
else
throw Exception("invalide input number of arguments");
}
else if (A.dimensions().lastNotOne() == 3) { // choose QImage::Format_RGB32 or Format_ARGB32
if (argCopy.size() == 2) {
QImage img = imwriteHelperRGB32(convert2uint8(A));
if (!imgWriter.write(QImage(img)))
throw Exception("cannot create image file" + FileName);
}
else if (argCopy.size() == 3) {
Array trans(argCopy[2]);
if (A.rows() == trans.rows() && A.columns() == trans.columns() ) {
// the third argument is alpha channel
QImage img = imwriteHelperARGB32(convert2uint8(A), convert2uint8(trans));
if (!imgWriter.write(QImage(img)))
throw Exception("cannot create image file" + FileName);
}
else {
if (trans.length() != 0)
eval->warningMessage("ignore colormap argument");
QImage img = imwriteHelperRGB32(convert2uint8(A));
if (!imgWriter.write(QImage(img)))
throw Exception("cannot create image file" + FileName);
}
}
else if (argCopy.size() == 4 || (argCopy.size() == 5 && hasAlpha == 1)) {
Array ctable(arg[2]);
if (ctable.length() != 0)
eval->warningMessage("ignore colormap argument");
Array trans(argCopy[3+hasAlpha]);
if (A.rows() == trans.rows() && A.columns() == trans.columns() ) {
// the third argument is alpha/transparent channel
QImage img = imwriteHelperARGB32(convert2uint8(A), convert2uint8(trans));
if (!imgWriter.write(QImage(img)))
throw Exception("alpha/transparent size is not the same as image size");
}
else {
if (trans.length() != 0)
eval->warningMessage("ignore invalid alpha/transparent argument");
QImage img = imwriteHelperRGB32(convert2uint8(A));
if (!imgWriter.write(QImage(img)))
throw Exception("cannot create image file" + FileName);
}
}
else
throw Exception("invalide input number of arguments");
}
else
throw Exception("invalid matrix dimension");
return ArrayVector();
}
|