File: colormapper.cpp

package info (click to toggle)
aoflagger 2.13.0-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 4,232 kB
  • sloc: cpp: 61,805; python: 60; sh: 23; makefile: 8
file content (529 lines) | stat: -rw-r--r-- 16,739 bytes parent folder | download | duplicates (2)
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

#include "structures/colormap.h"
#include "msio/fitsfile.h"
#include "structures/image2d.h"
#include "msio/pngfile.h"

#include "util/ffttools.h"

using namespace std;

struct ImageInfo { unsigned index; long double variance; };

bool operator<(const ImageInfo &a, const ImageInfo &b) {
	return a.variance > b.variance; // note that a noise image is "smaller" than a clean image
}

void addFits(Image2D *red, Image2D *green, Image2D *blue, Image2D *mono, const std::string &filename);

void HLStoRGB(long double hue,long double lum,long double sat,long double &red,long double &green, long double &blue);
void WLtoRGB(long double wavelength,long double &red,long double &green, long double &blue);
inline void ScaledWLtoRGB(long double position,long double &red,long double &green, long double &blue)
{
	WLtoRGB(position*300.0+400.0,red,green,blue);
	if(red < 0.0) red = 0.0;
	if(red > 1.0) red = 1.0;
	if(green < 0.0) green = 0.0;
	if(green > 1.0) green = 1.0;
	if(blue < 0.0) blue = 0.0;
	if(blue > 1.0) blue = 1.0;
}
void ReportRMS(Image2D *image);

int main(int argc, char *argv[])
{
	int pindex = 1;
	// parameters
	bool useSpectrum = true, blackWhite = false, mapColours = false;
	std::string colourMapName = "";
	std::unique_ptr<ColorMap> map = 0;
	bool colormap = false;
	int removeNoiseImages = 0;
	bool fft = false;
	enum ScaleMethod { MaximumContrast, Constant } scaleMethod = MaximumContrast;
	long double scaleValue = 1.0;
	std::string subtractFile, outputFitsFile, outputPngFile;
	bool subtract = false, redblue = false, rms = false, individualMaximization = false, displayMax = false, singleImage = false;
	bool window = false, cutWindow = false, saveFits = false, savePng = false;
	size_t windowX = 0, windowY = 0, windowWidth = 0, windowHeight = 0;
	size_t cutWindowX = 0, cutWindowY = 0, cutWindowWidth = 0, cutWindowHeight = 0;
	size_t singleImageIndex = 0;

	while(pindex < argc && argv[pindex][0] == '-') {
		string parameter = argv[pindex]+1;
		if(parameter == "s") { useSpectrum = true; }
		else if(parameter == "bw") { blackWhite = true; }
		else if(parameter == "c") { useSpectrum = false; }
		else if(parameter == "d") { ++pindex; subtractFile = argv[pindex]; subtract=true; }
		else if(parameter == "fft") { fft = true; }
		else if(parameter == "fi") { individualMaximization = true; }
		else if(parameter == "fits") {
			saveFits = true;
			++pindex; outputFitsFile = argv[pindex];
		}
		else if(parameter == "fm") { scaleMethod = MaximumContrast; }
		else if(parameter == "fv") { scaleMethod = Constant; ++pindex; scaleValue = atof(argv[pindex]); }
		else if(parameter == "m") { colormap = true; }
		else if(parameter == "max") { displayMax=true; }
		else if(parameter == "mc") { mapColours = true; ++pindex; colourMapName = argv[pindex]; }
		else if(parameter == "png")
		{
			savePng = true;
			++pindex; outputPngFile = argv[pindex];
		}
		else if(parameter == "r") { ++pindex; removeNoiseImages = atoi(argv[pindex]); }
		else if(parameter == "rb") { redblue=true; }
		else if(parameter == "rms") { rms=true; }
		else if(parameter == "si")
		{
			singleImage = true;
			++pindex; singleImageIndex = atoi(argv[pindex]);
		}
		else if(parameter == "w") {
			window = true;
			++pindex; windowX = atoi(argv[pindex]);
			++pindex; windowY = atoi(argv[pindex]);
			++pindex; windowWidth = atoi(argv[pindex]);
			++pindex; windowHeight = atoi(argv[pindex]);
		}
		else if(parameter == "wc") {
			cutWindow = true;
			++pindex; cutWindowX = atoi(argv[pindex]);
			++pindex; cutWindowY = atoi(argv[pindex]);
			++pindex; cutWindowWidth = atoi(argv[pindex]);
			++pindex; cutWindowHeight = atoi(argv[pindex]);
		}
		else {
			cerr << "Unknown parameter: -" << parameter << endl;
			return -1;
		}
		++pindex;
	}

	if(argc-pindex < 1) {
		cerr << "Usage: \n\t" << argv[0] << " [options] <input fits file>\n"
				"\toptions:\n"
				"\t-d <fitsfile> subtract the file from the image\n"
				"\t-fft perform fft before combining\n"
				"\t-fi maximize each individual image before summing\n"
				"\t-fits <file> store in fits file (does not preserve the headers)\n"
				"\t-fm scale colors for maximum contrast, upper 0.02% of the data will be oversaturated (default)\n"
				"\t-fv <value> scale so that <value> flux is full brightness\n"
				"\t-m add colormap to image\n"
				"\t-max display maximum of each image\n"
				"\t-png <file> save as png file\n"
				"\t-rb don't use frequency colored, but use red/blue map for positive/negative values\n"
				"\t-rms calculate and show the rms of the upperleft 10% data\n"
				"\t-s use spectrum (default)\n"
				"\t-si <index> select single image from each fits file\n"
				"\t-c use color circle\n"
				"\t-w <x> <y> <width> <height> select a window of each frame only\n"
				"\t-wc <x> <y> <width> <height> cut a window in each frame\n";
		return -1;
	}

	Image2D
		*red = nullptr,
		*green = nullptr,
		*blue = nullptr,
		*mono = nullptr;

	long double totalRed = 0.0, totalGreen = 0.0, totalBlue = 0.0;
	unsigned addedCount = 0;
	
	if(mapColours)
	{
		map = ColorMap::CreateColorMap(colourMapName);
	}
	
	size_t inputCount = argc-pindex;
	for(unsigned inputIndex=pindex;inputIndex<(unsigned) argc;++inputIndex)
	{
		cout << "Opening " << argv[inputIndex] << "..." << endl;
		FitsFile fitsfile(argv[inputIndex]);
		fitsfile.Open(FitsFile::ReadOnlyMode);
		fitsfile.MoveToHDU(1);
		unsigned images = Image2D::GetImageCountInHUD(fitsfile);

		FitsFile *subtractFits = 0;
		if(subtract) {
			cout << "Opening " << subtractFile << "..." << endl;
			subtractFits = new FitsFile(subtractFile);
			subtractFits->Open(FitsFile::ReadOnlyMode);
			subtractFits->MoveToHDU(1);
			unsigned sImages = Image2D::GetImageCountInHUD(fitsfile);
			if(sImages < images)
				images = sImages;
		}

		std::vector<ImageInfo> variances;

		if(removeNoiseImages > 0) {
			cout << "Sorting images on noise level..." << endl;
			for(unsigned i=0;i<images;++i)
			{
				if(i % 8 == 0) {
					unsigned upper = i+9;
					if(upper > images) upper = images;
					cout << "Measuring noise level in images " << (i+1) << " - " << upper << "..." << endl;
				}
				Image2D image(Image2D::MakeFromFits(fitsfile, i));
				struct ImageInfo imageInfo;
				imageInfo.variance = image.GetRMS();
				imageInfo.index = i;
				variances.push_back(imageInfo);
			}
			sort(variances.begin(), variances.end());

			cout << "The following images are removed because of too much noise: "
					<< variances.front().index;
			for(std::vector<ImageInfo>::const_iterator i=variances.begin()+1;i<variances.begin()+removeNoiseImages;++i)
			{
				cout << ", " << i->index;
			}
			cout << endl;
		}

		unsigned lowI, highI;
		if(singleImage)
		{
			lowI = singleImageIndex;
			highI = singleImageIndex+1;
		} else {
			lowI = 0;
			highI = images;
		}
			
		for(unsigned i=lowI;i<highI;++i)
		{
			if(i % 8 == 0) {
				unsigned upper = i+9;
				if(upper > images) upper = images;
				cout << "Adding image " << (i+1) << " - " << upper << "..." << endl;
			}
			bool skip = false;
			if(removeNoiseImages > 0) {
				for(std::vector<ImageInfo>::const_iterator j=variances.begin();j<variances.begin()+removeNoiseImages;++j)
				{
					if(j->index == i) { skip = true; break; }
				}
			}
			if(!skip) {
				long double wavelengthRatio;
				if(images*inputCount > 1)
					wavelengthRatio = (1.0 - (long double) (i+((int) inputIndex-(int) pindex)*images) / (images*inputCount-1.0));
				else
					wavelengthRatio = 0.5;
				std::cout << "ratio=" << wavelengthRatio << '\n';
				Image2D image(Image2D::MakeFromFits(fitsfile, i));
				if(subtract)
				{
					Image2D imageB(Image2D::MakeFromFits(*subtractFits, i));
					image = Image2D::MakeFromDiff(image, imageB);
				}
				if(window)
				{
					Image2D empty(Image2D::MakeZeroImage(image.Width(), image.Height()));
					for(unsigned y=image.Height()-windowY-windowHeight;y<image.Height()-windowY;++y)
					{
						for(unsigned x=windowX;x<windowX+windowWidth;++x)
							empty.SetValue(x, y, image.Value(x, y));
					}
					image = empty;
				}
				if(cutWindow)
				{
					for(unsigned y=image.Height()-cutWindowY-cutWindowHeight;y<image.Height()-cutWindowY;++y)
					{
						for(unsigned x=cutWindowX;x<cutWindowX+cutWindowWidth;++x)
							image.SetValue(x, y, 0.0);
					}
				}
				if(fft) {
					Image2D *fft = FFTTools::CreateFFTImage(image, FFTTools::Absolute);
					Image2D *fullfft = FFTTools::CreateFullImageFromFFT(*fft);
					delete fft;
					image = *fullfft;
				}
				long double max;
				if(individualMaximization) {
					max = image.GetMaximum();
					if(max <= 0.0) max = 1.0;
				} else {
					max = 1.0;
				}
				if(displayMax)
					cout << "max=" << image.GetMinimum() << ":" << image.GetMaximum() << endl; 
				if(rms)
					ReportRMS(&image);
				long double r=0.0,g=0.0,b=0.0;
				if(blackWhite || mapColours) {
					r = 1.0; b = 1.0; g = 1.0;
				}
				else if(redblue) {
					r = 1.0;
					b = 1.0;
				} else if(useSpectrum)
					ScaledWLtoRGB(wavelengthRatio, r, g, b);
				else
					HLStoRGB(wavelengthRatio, 0.5, 1.0, r, g, b);
				totalRed += r;
				totalGreen += g;
				totalBlue += b;
				if(red == 0) {
					red = new Image2D(Image2D::MakeZeroImage(image.Width(), image.Height()));
					green = new Image2D(Image2D::MakeZeroImage(image.Width(), image.Height()));
					blue = new Image2D(Image2D::MakeZeroImage(image.Width(), image.Height()));
					mono = new Image2D(Image2D::MakeZeroImage(image.Width(), image.Height()));
				}
				size_t minY = image.Height(), minX = image.Width();
				if(red->Height() < minY) minY = red->Height();
				if(red->Width() < minX) minX = red->Width();
				for(unsigned y=0;y<minY;++y)
				{
					for(unsigned x=0;x<minX;++x)	
					{
						long double value = image.Value(x, y);
						mono->AddValue(x, y, value);
						if(mapColours) {
							double mapVal = 2.0*value/max/scaleValue-1.0;
							if(mapVal < -1.0) mapVal = -1.0;
							if(mapVal > 1.0) mapVal = 1.0;
							red->AddValue(x, y, map->ValueToColorR(mapVal)/255.0);
							blue->AddValue(x, y, map->ValueToColorB(mapVal)/255.0); 
							green->AddValue(x, y, map->ValueToColorG(mapVal)/255.0); 
						}
						else if(blackWhite) {
							red->AddValue(x, y, value/max);
							blue->AddValue(x, y, value/max); 
							green->AddValue(x, y, value/max); 
						}
						else if(redblue) {
							if(value > 0)
								red->AddValue(x, y, value/max);
							else
								blue->AddValue(x, y, value/(-max)); 
						}
						else {
							if(value < 0.0) value = 0.0;
							value /= max;
							if(colormap && (y < 96 && y >= 32 && x < images*8)) { 
								if(x >= i*8 && x < i*8+8) {
									red->SetValue(x, y, r * images);
									green->SetValue(x, y, g * images);
									blue->SetValue(x, y, b * images);
								}
							} else {
								red->AddValue(x, y, r * value);
								green->AddValue(x, y, g * value);
								blue->AddValue(x, y, b * value);
							}
						}
					}
				}
				++addedCount;
			}
		}
		
		if(subtract) {
			subtractFits->Close();
			delete subtractFits;
		}
	}
		
	cout << "Scaling to ordinary units..." << endl;
	for(unsigned y=0;y<red->Height();++y) {
		for(unsigned x=0;x<red->Width();++x) {
			red->SetValue(x, y, red->Value(x, y) / addedCount);
			blue->SetValue(x, y, blue->Value(x, y) / addedCount);
			green->SetValue(x, y, green->Value(x, y) / addedCount);
			mono->SetValue(x, y, mono->Value(x, y) / addedCount);
		}
	}

	if(rms) {
		ReportRMS(mono);
	}
	
	if(saveFits)
	{
		cout << "Saving fits file..." << endl;
		mono->SaveToFitsFile(outputFitsFile);
	}

	if(savePng)
	{
		cout << "Normalizing..." << endl;
		long double maxRed, maxGreen, maxBlue;
		switch(scaleMethod) {
			default:
			case MaximumContrast:
				maxRed = red->GetTresholdForCountAbove(red->Width() * red->Height() / 5000);
				maxGreen = green->GetTresholdForCountAbove(green->Width() * green->Height() / 5000);
				maxBlue = blue->GetTresholdForCountAbove(blue->Width() * blue->Height() / 5000);
			break;
			case Constant:
				if(!mapColours)
				{
					maxRed = scaleValue;
					maxGreen = scaleValue * totalGreen / totalRed;
					maxBlue = scaleValue * totalBlue / totalRed;
				}
				else {
					maxRed = 1.0; maxGreen = 1.0; maxBlue = 1.0;
				}
			break; 
		}
		if(maxRed <= 0.0) maxRed = 1.0;
		if(maxGreen <= 0.0) maxGreen = 1.0;
		if(maxBlue <= 0.0) maxBlue = 1.0;
		cout << "Contrast stretch value for red: " << maxRed << endl; 
		
		PngFile file(outputPngFile, red->Width(), red->Height());
		file.BeginWrite();

		cout << "Writing " << outputPngFile << "..." << endl;
		for(unsigned y=0;y<red->Height();++y)
		{
			for(unsigned x=0;x<red->Width();++x)	
			{
				unsigned
					r = (unsigned) ((red->Value(x, y) / maxRed) * 255.0),
					g = (unsigned) ((green->Value(x, y) / maxGreen) * 255.0),
					b = (unsigned) ((blue->Value(x, y) / maxBlue) * 255.0);
				if(r > 255) r = 255;
				if(g > 255) g = 255;
				if(b > 255) b = 255;
				if(red->Value(x, y) < 0) r = 0;
				if(green->Value(x, y) < 0) g = 0;
				if(blue->Value(x, y) < 0) b = 0;
				file.PlotDatapoint(x, red->Height() - 1 - y, r, g, b, 255);
			}
		}
		file.Close();
	}
	
	delete red;
	delete green;
	delete blue;
	delete mono;

  return EXIT_SUCCESS;
}

/* utility routine for HLStoRGB */ 
long double HueToRGB(long double p,long double q,long double tc)
{
	/* range check: note values passed add/subtract thirds of range */ 
	if (tc < 0)
			tc += 1.0;

	if (tc > 1.0)
			tc -= 1.0;

	/* return r,g, or b value from this tridrant */ 
	if (tc < (1.0/6.0))
			return ( p + (q-p)*6.0*tc);
	if (tc < 0.5)
			return ( q );
	if (tc < 2.0/3.0)
			return ( p + (q-p)*6.0*(2.0/3.0 - tc));
	else
			return ( p );
}

void HLStoRGB(long double hue,long double lum,long double sat,long double &red,long double &green, long double &blue)
{
	if (sat == 0) {
			red=green=blue=lum;
		}
	else  {
			long double q,p;
			if (lum < 0.5)
				q = lum*(1.0 + sat);
			else
				q = lum + sat - (lum*sat);
			p = 2.0*lum-q;

			red = HueToRGB(p,q,hue+1.0/3.0);
			green = HueToRGB(p,q,hue);
			blue = HueToRGB(p,q,hue-1.0/3.0);
	}
}

void WLtoRGB(long double wavelength,long double &red,long double &green, long double &blue)
{
  if(wavelength >= 350.0 && wavelength <= 439.0) {
   red	= -(wavelength - 440.0) / (440.0 - 350.0);
   green = 0.0;
   blue	= 1.0;
  } else if(wavelength >= 440.0 && wavelength <= 489.0) {
   red	= 0.0;
   green = (wavelength - 440.0) / (490.0 - 440.0);
   blue	= 1.0;
  } else if(wavelength >= 490.0 && wavelength <= 509.0) {
   red = 0.0;
   green = 1.0;
   blue = -(wavelength - 510.0) / (510.0 - 490.0);
  } else if(wavelength >= 510.0 && wavelength <= 579.0) { 
   red = (wavelength - 510.0) / (580.0 - 510.0);
   green = 1.0;
   blue = 0.0;
  } else if(wavelength >= 580.0 && wavelength <= 644.0) {
   red = 1.0;
   green = -(wavelength - 645.0) / (645.0 - 580.0);
   blue = 0.0;
  } else if(wavelength >= 645.0 && wavelength <= 780.0) {
   red = 1.0;
   green = 0.0;
   blue = 0.0;
  } else {
   red = 1.0;
   green = 0.0;
   blue = 0.0;
  }
  if(wavelength >= 350.0 && wavelength <= 419.0) {
	  long double factor;
    factor = 0.3 + 0.7*(wavelength - 350.0) / (420.0 - 350.0);
		red *= factor;
		green *= factor;
		blue *= factor;
  } else if(wavelength >= 420.0 && wavelength <= 700.0) {
    // nothing to be done
  } else if(wavelength >= 701.0 && wavelength <= 780.0) {
	  long double factor;
    factor = 0.3 + 0.7*(780.0 - wavelength) / (780.0 - 700.0);
		red *= factor;
		green *= factor;
		blue *= factor;
  } else if(wavelength >= 780.0) {
    long double factor;
    factor = 0.3;
    red *= factor;
    green *= factor;
    blue *= factor;
  } else {
		red = 0.0;
		green = 0.0;
		blue = 0.0;
 }
}

void ReportRMS(Image2D *image)
{
	unsigned squareWidth = image->Width()/5;
	unsigned squareHeight = image->Height()/5;
	cout << "Calculating rms... " << endl;
	cout << "Total RMS=" << image->GetRMS()*1000.0L << "mJ" << endl;
	cout << "Center RMS=" << image->GetRMS(image->Width()/2-squareWidth/2,image->Height()/2-squareHeight/2, squareWidth, squareHeight)*1000.0L << "mJ" << endl;
	cout << "Upperleft RMS=" << image->GetRMS(0, 0, squareWidth, squareHeight)*1000.0L << "mJ" << endl;
	cout << "Upperright RMS=" << image->GetRMS(image->Width()-squareWidth, 0, squareWidth, squareHeight) * 1000.0L << "mJ" << endl;
	cout << "Lowerleft RMS=" << image->GetRMS(0, image->Height()-squareHeight, squareWidth, squareHeight) * 1000.0L << "mJ" << endl;
	cout << "Lowerright RMS=" << image->GetRMS(image->Width()-squareWidth, image->Height()-squareHeight, squareWidth, squareHeight) *1000.0L << "mJ" << endl;
	cout << "Minimum intensity=" << image->GetMinimum() * 1000.0L << "mJ" << endl;
	cout << "Maximum intensity=" << image->GetMaximum() * 1000.0L << "mJ" << endl;
}