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 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
|
//Qt Includes
#include <QFileInfo>
//Project Includes
#include "fileio.h"
fileio::fileio()
{
debayerParams.method = DC1394_BAYER_METHOD_NEAREST;
debayerParams.filter = DC1394_COLOR_FILTER_RGGB;
debayerParams.offsetX = debayerParams.offsetY = 0;
}
fileio::~fileio()
{
if(m_ImageBuffer && !imageBufferTaken)
deleteImageBuffer();
}
void fileio::deleteImageBuffer()
{
if(m_ImageBuffer)
{
delete[] m_ImageBuffer;
m_ImageBuffer = nullptr;
}
}
bool fileio::loadImage(QString fileName)
{
justLoadBuffer = false;
QFileInfo newFileInfo(fileName);
bool success = false;
if(newFileInfo.suffix() == "fits" || newFileInfo.suffix() == "fit")
success = loadFits(fileName);
else
success = loadOtherFormat(fileName);
if(success)
generateQImage();
return success;
}
bool fileio::loadImageBufferOnly(QString fileName)
{
justLoadBuffer = true;
QFileInfo newFileInfo(fileName);
bool success = false;
if(newFileInfo.suffix() == "fits" || newFileInfo.suffix() == "fit")
success = loadFits(fileName);
else
success = loadOtherFormat(fileName);
return success;
}
//This method was copied and pasted and modified from the method privateLoad in fitsdata in KStars
//It loads a FITS file, reads the FITS Headers, and loads the data from the image
bool fileio::loadFits(QString fileName)
{
file = fileName;
int status = 0, anynullptr = 0;
long naxes[3];
// Use open diskfile as it does not use extended file names which has problems opening
// files with [ ] or ( ) in their names.
if (fits_open_diskfile(&fptr, file.toLocal8Bit(), READONLY, &status))
{
logIssue(QString("Error opening fits file %1").arg(file));
return false;
}
else
stats.size = QFile(file).size();
if (fits_movabs_hdu(fptr, 1, IMAGE_HDU, &status))
{
logIssue(QString("Could not locate image HDU."));
fits_close_file(fptr, &status);
return false;
}
int fitsBitPix = 0;
if (fits_get_img_param(fptr, 3, &fitsBitPix, &(stats.ndim), naxes, &status))
{
logIssue(QString("FITS file open error (fits_get_img_param)."));
fits_close_file(fptr, &status);
return false;
}
if (stats.ndim < 2)
{
logIssue("1D FITS images are not supported.");
fits_close_file(fptr, &status);
return false;
}
switch (fitsBitPix)
{
case BYTE_IMG:
stats.dataType = SEP_TBYTE;
stats.bytesPerPixel = sizeof(uint8_t);
break;
case SHORT_IMG:
// Read SHORT image as USHORT
stats.dataType = TUSHORT;
stats.bytesPerPixel = sizeof(int16_t);
break;
case USHORT_IMG:
stats.dataType = TUSHORT;
stats.bytesPerPixel = sizeof(uint16_t);
break;
case LONG_IMG:
// Read LONG image as ULONG
stats.dataType = TULONG;
stats.bytesPerPixel = sizeof(int32_t);
break;
case ULONG_IMG:
stats.dataType = TULONG;
stats.bytesPerPixel = sizeof(uint32_t);
break;
case FLOAT_IMG:
stats.dataType = TFLOAT;
stats.bytesPerPixel = sizeof(float);
break;
case LONGLONG_IMG:
stats.dataType = TLONGLONG;
stats.bytesPerPixel = sizeof(int64_t);
break;
case DOUBLE_IMG:
stats.dataType = TDOUBLE;
stats.bytesPerPixel = sizeof(double);
break;
default:
logIssue(QString("Bit depth %1 is not supported.").arg(fitsBitPix));
fits_close_file(fptr, &status);
return false;
}
if (stats.ndim < 3)
naxes[2] = 1;
if (naxes[0] == 0 || naxes[1] == 0)
{
logIssue(QString("Image has invalid dimensions %1x%2").arg(naxes[0]).arg(naxes[1]));
}
stats.width = static_cast<uint16_t>(naxes[0]);
stats.height = static_cast<uint16_t>(naxes[1]);
stats.channels = static_cast<uint8_t>(naxes[2]);
stats.samples_per_channel = stats.width * stats.height;
m_ImageBufferSize = stats.samples_per_channel * stats.channels * static_cast<uint16_t>(stats.bytesPerPixel);
deleteImageBuffer();
m_ImageBuffer = new uint8_t[m_ImageBufferSize];
if (m_ImageBuffer == nullptr)
{
logIssue(QString("FITSData: Not enough memory for image_buffer channel. Requested: %1 bytes ").arg(m_ImageBufferSize));
fits_close_file(fptr, &status);
return false;
}
long nelements = stats.samples_per_channel * stats.channels;
if (fits_read_img(fptr, static_cast<uint16_t>(stats.dataType), 1, nelements, nullptr, m_ImageBuffer, &anynullptr, &status))
{
logIssue("Error reading image.");
fits_close_file(fptr, &status);
return false;
}
if( !justLoadBuffer )
{
if(checkDebayer())
debayer();
getSolverOptionsFromFITS();
parseHeader();
}
fits_close_file(fptr, &status);
return true;
}
//This method I wrote combining code from the fits loading method above, the fits debayering method below, and QT
//I also consulted the ImageToFITS method in fitsdata in KStars
//The goal of this method is to load the data from a file that is not FITS format
bool fileio::loadOtherFormat(QString fileName)
{
file = fileName;
QImageReader fileReader(file.toLocal8Bit());
if (!fileReader.canRead())
{
logIssue(QString("Cannot open '%1' (%2)\n").arg(file, fileReader.errorString()));
return false;
}
QImage imageFromFile;
if(!fileReader.read(&imageFromFile))
{
logIssue("Failed to open image.\n");
return false;
}
imageFromFile = imageFromFile.convertToFormat(QImage::Format_RGB32);
// because we convert it to 32bit-packed RGB with each color 8 bit, we can hardcode this here
stats.bytesPerPixel = 1;
stats.dataType = SEP_TBYTE;
stats.width = static_cast<uint16_t>(imageFromFile.width());
stats.height = static_cast<uint16_t>(imageFromFile.height());
stats.channels = 3;
stats.ndim = 3;
stats.samples_per_channel = stats.width * stats.height;
m_ImageBufferSize = stats.samples_per_channel * stats.channels * static_cast<uint16_t>(stats.bytesPerPixel);
deleteImageBuffer();
m_ImageBuffer = new uint8_t[m_ImageBufferSize];
if (m_ImageBuffer == nullptr)
{
logIssue(QString("FITSData: Not enough memory for image_buffer channel. Requested: %1 bytes ").arg(m_ImageBufferSize));
return false;
}
auto debayered_buffer = reinterpret_cast<uint8_t *>(m_ImageBuffer);
auto * original_bayered_buffer = reinterpret_cast<uint8_t *>(imageFromFile.bits());
// Data in RGB32, with bytes in the order of B,G,R,A, we need to copy them into 3 layers for FITS
uint8_t * rBuff = debayered_buffer;
uint8_t * gBuff = debayered_buffer + (stats.width * stats.height);
uint8_t * bBuff = debayered_buffer + (stats.width * stats.height * 2);
int imax = stats.samples_per_channel * 4 - 4;
for (int i = 0; i <= imax; i += 4)
{
*rBuff++ = original_bayered_buffer[i + 2];
*gBuff++ = original_bayered_buffer[i + 1];
*bBuff++ = original_bayered_buffer[i + 0];
}
return true;
}
//This method was copied and pasted from Fitsdata in KStars
//It gets the bayer pattern information from the FITS header
bool fileio::checkDebayer()
{
int status = 0;
char bayerPattern[64];
// Let's search for BAYERPAT keyword, if it's not found we return as there is no bayer pattern in this image
if (fits_read_keyword(fptr, "BAYERPAT", bayerPattern, nullptr, &status))
return false;
if (stats.dataType != TUSHORT && stats.dataType != SEP_TBYTE)
{
logIssue("Only 8 and 16 bits bayered images supported.");
return false;
}
QString pattern(bayerPattern);
pattern = pattern.remove('\'').trimmed();
if (pattern == "RGGB")
debayerParams.filter = DC1394_COLOR_FILTER_RGGB;
else if (pattern == "GBRG")
debayerParams.filter = DC1394_COLOR_FILTER_GBRG;
else if (pattern == "GRBG")
debayerParams.filter = DC1394_COLOR_FILTER_GRBG;
else if (pattern == "BGGR")
debayerParams.filter = DC1394_COLOR_FILTER_BGGR;
// We return unless we find a valid pattern
else
{
logIssue(QString("Unsupported bayer pattern %1.").arg(pattern));
return false;
}
fits_read_key(fptr, TINT, "XBAYROFF", &debayerParams.offsetX, nullptr, &status);
fits_read_key(fptr, TINT, "YBAYROFF", &debayerParams.offsetY, nullptr, &status);
//HasDebayer = true;
return true;
}
//This method was copied and pasted from Fitsdata in KStars
//It debayers the image using the methods below
bool fileio::debayer()
{
switch (stats.dataType)
{
case SEP_TBYTE:
return debayer_8bit();
case TUSHORT:
return debayer_16bit();
default:
return false;
}
}
//This method was copied and pasted from Fitsdata in KStars
//This method debayers 8 bit images
bool fileio::debayer_8bit()
{
dc1394error_t error_code;
uint32_t rgb_size = stats.samples_per_channel * 3 * stats.bytesPerPixel;
auto * destinationBuffer = new uint8_t[rgb_size];
auto * bayer_source_buffer = reinterpret_cast<uint8_t *>(m_ImageBuffer);
auto * bayer_destination_buffer = reinterpret_cast<uint8_t *>(destinationBuffer);
if (bayer_destination_buffer == nullptr)
{
logIssue("Unable to allocate memory for temporary bayer buffer.");
return false;
}
int ds1394_height = stats.height;
auto dc1394_source = bayer_source_buffer;
if (debayerParams.offsetY == 1)
{
dc1394_source += stats.width;
ds1394_height--;
}
if (debayerParams.offsetX == 1)
{
dc1394_source++;
}
error_code = dc1394_bayer_decoding_8bit(dc1394_source, bayer_destination_buffer, stats.width, ds1394_height,
debayerParams.filter,
debayerParams.method);
if (error_code != DC1394_SUCCESS)
{
logIssue(QString("Debayer failed (%1)").arg(error_code));
stats.channels = 1;
delete[] destinationBuffer;
return false;
}
if (m_ImageBufferSize != rgb_size)
{
delete[] m_ImageBuffer;
m_ImageBuffer = new uint8_t[rgb_size];
if (m_ImageBuffer == nullptr)
{
delete[] destinationBuffer;
logIssue("Unable to allocate memory for temporary bayer buffer.");
return false;
}
m_ImageBufferSize = rgb_size;
}
auto bayered_buffer = reinterpret_cast<uint8_t *>(m_ImageBuffer);
// Data in R1G1B1, we need to copy them into 3 layers for FITS
uint8_t * rBuff = bayered_buffer;
uint8_t * gBuff = bayered_buffer + (stats.width * stats.height);
uint8_t * bBuff = bayered_buffer + (stats.width * stats.height * 2);
int imax = stats.samples_per_channel * 3 - 3;
for (int i = 0; i <= imax; i += 3)
{
*rBuff++ = bayer_destination_buffer[i];
*gBuff++ = bayer_destination_buffer[i + 1];
*bBuff++ = bayer_destination_buffer[i + 2];
}
delete[] destinationBuffer;
return true;
}
//This method was copied and pasted from Fitsdata in KStars
//This method debayers 16 bit images
bool fileio::debayer_16bit()
{
dc1394error_t error_code;
uint32_t rgb_size = stats.samples_per_channel * 3 * stats.bytesPerPixel;
auto * destinationBuffer = new uint8_t[rgb_size];
auto * bayer_source_buffer = reinterpret_cast<uint16_t *>(m_ImageBuffer);
auto * bayer_destination_buffer = reinterpret_cast<uint16_t *>(destinationBuffer);
if (bayer_destination_buffer == nullptr)
{
logIssue("Unable to allocate memory for temporary bayer buffer.");
return false;
}
int ds1394_height = stats.height;
auto dc1394_source = bayer_source_buffer;
if (debayerParams.offsetY == 1)
{
dc1394_source += stats.width;
ds1394_height--;
}
if (debayerParams.offsetX == 1)
{
dc1394_source++;
}
error_code = dc1394_bayer_decoding_16bit(dc1394_source, bayer_destination_buffer, stats.width, ds1394_height,
debayerParams.filter,
debayerParams.method, 16);
if (error_code != DC1394_SUCCESS)
{
logIssue(QString("Debayer failed (%1)").arg(error_code));
stats.channels = 1;
delete[] destinationBuffer;
return false;
}
if (m_ImageBufferSize != rgb_size)
{
delete[] m_ImageBuffer;
m_ImageBuffer = new uint8_t[rgb_size];
if (m_ImageBuffer == nullptr)
{
delete[] destinationBuffer;
logIssue("Unable to allocate memory for temporary bayer buffer.");
return false;
}
m_ImageBufferSize = rgb_size;
}
auto bayered_buffer = reinterpret_cast<uint16_t *>(m_ImageBuffer);
// Data in R1G1B1, we need to copy them into 3 layers for FITS
uint16_t * rBuff = bayered_buffer;
uint16_t * gBuff = bayered_buffer + (stats.width * stats.height);
uint16_t * bBuff = bayered_buffer + (stats.width * stats.height * 2);
int imax = stats.samples_per_channel * 3 - 3;
for (int i = 0; i <= imax; i += 3)
{
*rBuff++ = bayer_destination_buffer[i];
*gBuff++ = bayer_destination_buffer[i + 1];
*bBuff++ = bayer_destination_buffer[i + 2];
}
delete[] destinationBuffer;
return true;
}
//This method is copied and pasted and modified from getSolverOptionsFromFITS in Align in KStars
//Then it was split in two parts, the other part was sent to the ExternalExtractorSolver class since the internal solver doesn't need it
//This part extracts the options from the FITS file and prepares them for use by the internal or external solver
bool fileio::getSolverOptionsFromFITS()
{
int status = 0, fits_ccd_width, fits_ccd_height, fits_binx = 1, fits_biny = 1;
char comment[128], error_status[512];
fitsfile *fptr = nullptr;
double fits_fov_x, fits_fov_y, fov_lower, fov_upper, fits_ccd_hor_pixel = -1,
fits_ccd_ver_pixel = -1, fits_focal_length = -1;
status = 0;
// Use open diskfile as it does not use extended file names which has problems opening
// files with [ ] or ( ) in their names.
if (fits_open_diskfile(&fptr, file.toLocal8Bit(), READONLY, &status))
{
fits_report_error(stderr, status);
fits_get_errstatus(status, error_status);
logIssue(QString::fromUtf8(error_status));
return false;
}
status = 0;
if (fits_movabs_hdu(fptr, 1, IMAGE_HDU, &status))
{
fits_report_error(stderr, status);
fits_get_errstatus(status, error_status);
logIssue(QString::fromUtf8(error_status));
fits_close_file(fptr, &status);
return false;
}
status = 0;
if (fits_read_key(fptr, TINT, "NAXIS1", &fits_ccd_width, comment, &status))
{
fits_report_error(stderr, status);
fits_get_errstatus(status, error_status);
logIssue("FITS header: cannot find NAXIS1.");
fits_close_file(fptr, &status);
return false;
}
status = 0;
if (fits_read_key(fptr, TINT, "NAXIS2", &fits_ccd_height, comment, &status))
{
fits_report_error(stderr, status);
fits_get_errstatus(status, error_status);
logIssue("FITS header: cannot find NAXIS2.");
fits_close_file(fptr, &status);
return false;
}
bool coord_ok = true;
status = 0;
char objectra_str[32];
if (fits_read_key(fptr, TSTRING, "OBJCTRA", objectra_str, comment, &status))
{
if (fits_read_key(fptr, TDOUBLE, "RA", &ra, comment, &status))
{
fits_report_error(stderr, status);
fits_get_errstatus(status, error_status);
coord_ok = false;
logIssue(QString("FITS header: cannot find OBJCTRA (%1).").arg(QString(error_status)));
}
else
// Degrees to hours
ra /= 15;
}
else
{
dms raDMS = dms::fromString(objectra_str, false);
ra = raDMS.Hours();
}
status = 0;
char objectde_str[32];
if (coord_ok && fits_read_key(fptr, TSTRING, "OBJCTDEC", objectde_str, comment, &status))
{
if (fits_read_key(fptr, TDOUBLE, "DEC", &dec, comment, &status))
{
fits_report_error(stderr, status);
fits_get_errstatus(status, error_status);
coord_ok = false;
logIssue(QString("FITS header: cannot find OBJCTDEC (%1).").arg(QString(error_status)));
}
}
else
{
dms deDMS = dms::fromString(objectde_str, true);
dec = deDMS.Degrees();
}
if(coord_ok)
position_given = true;
status = 0;
double pixelScale = 0;
// If we have pixel scale in arcsecs per pixel then lets use that directly
// instead of calculating it from FOCAL length and other information
if (fits_read_key(fptr, TDOUBLE, "SCALE", &pixelScale, comment, &status) == 0)
{
double fov_low = 0.8 * pixelScale;
double fov_high = 1.2 * pixelScale;
scale_given = true;
scale_low = fov_low;
scale_high = fov_high;
scale_units = SSolver::ARCSEC_PER_PIX;
fits_close_file(fptr, &status);
return true;
}
if (fits_read_key(fptr, TDOUBLE, "FOCALLEN", &fits_focal_length, comment, &status))
{
int integer_focal_length = -1;
if (fits_read_key(fptr, TINT, "FOCALLEN", &integer_focal_length, comment, &status))
{
fits_report_error(stderr, status);
fits_get_errstatus(status, error_status);
logIssue(QString("FITS header: cannot find FOCALLEN: (%1).").arg(QString(error_status)));
fits_close_file(fptr, &status);
return false;
}
else
fits_focal_length = integer_focal_length;
}
status = 0;
if (fits_read_key(fptr, TDOUBLE, "PIXSIZE1", &fits_ccd_hor_pixel, comment, &status))
{
fits_report_error(stderr, status);
fits_get_errstatus(status, error_status);
logIssue(QString("FITS header: cannot find PIXSIZE1 (%1).").arg(QString(error_status)));
fits_close_file(fptr, &status);
return false;
}
status = 0;
if (fits_read_key(fptr, TDOUBLE, "PIXSIZE2", &fits_ccd_ver_pixel, comment, &status))
{
fits_report_error(stderr, status);
fits_get_errstatus(status, error_status);
logIssue(QString("FITS header: cannot find PIXSIZE2 (%1).").arg(QString(error_status)));
fits_close_file(fptr, &status);
return false;
}
status = 0;
fits_read_key(fptr, TINT, "XBINNING", &fits_binx, comment, &status);
status = 0;
fits_read_key(fptr, TINT, "YBINNING", &fits_biny, comment, &status);
// Calculate FOV
fits_fov_x = 206264.8062470963552 * fits_ccd_width * fits_ccd_hor_pixel / 1000.0 / fits_focal_length * fits_binx;
fits_fov_y = 206264.8062470963552 * fits_ccd_height * fits_ccd_ver_pixel / 1000.0 / fits_focal_length * fits_biny;
fits_fov_x /= 60.0;
fits_fov_y /= 60.0;
// let's stretch the boundaries by 10%
fov_lower = qMin(fits_fov_x, fits_fov_y);
fov_upper = qMax(fits_fov_x, fits_fov_y);
fov_lower *= 0.90;
fov_upper *= 1.10;
//Final Options that get stored.
scale_given = true;
scale_low = fov_lower;
scale_high = fov_upper;
scale_units = SSolver::ARCMIN_WIDTH;
fits_close_file(fptr, &status);
return true;
}
// This method was copied from KStars Fitsdata to get the fits headers for saving.
bool fileio::parseHeader()
{
char * header = nullptr;
int status = 0, nkeys = 0;
if (fits_hdr2str(fptr, 0, nullptr, 0, &header, &nkeys, &status))
{
fits_report_error(stderr, status);
free(header);
return false;
}
m_HeaderRecords.clear();
QString recordList = QString(header);
for (int i = 0; i < nkeys; i++)
{
Record oneRecord;
// Quotes cause issues for simplified below so we're removing them.
QString record = recordList.mid(i * 80, 80).remove("'");
QStringList properties = record.split(QRegularExpression("[=/]"));
// If it is only a comment
if (properties.size() == 1)
{
oneRecord.key = properties[0].mid(0, 7);
oneRecord.comment = properties[0].mid(8).simplified();
}
else
{
oneRecord.key = properties[0].simplified();
oneRecord.value = properties[1].simplified();
// Just in case the comment had / or = in it.
for(int prop = 2; prop<properties.size(); prop++)
{
oneRecord.comment += properties[prop].simplified();
if(prop < properties.size() - 1)
oneRecord.comment += " ";
}
// Try to guess the value.
// Test for integer & double. If neither, then leave it as "string".
bool ok = false;
// Is it Integer?
oneRecord.value.toInt(&ok);
if (ok)
oneRecord.value.convert(QMetaType::Int);
else
{
// Is it double?
oneRecord.value.toDouble(&ok);
if (ok)
oneRecord.value.convert(QMetaType::Double);
}
}
m_HeaderRecords.append(oneRecord);
}
#ifndef _WIN32 //This prevents a crash on windows. This should be fixed since the header should be freed!
free(header);
#endif
return true;
}
//This was copied and pasted and modified from ImageToFITS and injectWCS in fitsdata in KStars
bool fileio::saveAsFITS(QString fileName, FITSImage::Statistic &imageStats, uint8_t *imageBuffer, FITSImage::Solution solution, const QList<Record> &records, bool hasSolution)
{
int status = 0;
fitsfile * new_fptr;
//I am hoping that this is correct.
//I"m trying to set these two variables based on the ndim variable since this class doesn't have access to these variables.
long naxis;
int channels;
if (imageStats.ndim < 3)
{
channels = 1;
naxis = 2;
}
else
{
channels = 3;
naxis = 3;
}
long nelements;
long naxes[3] = { imageStats.width, imageStats.height, channels };
char error_status[512] = {0};
QFileInfo newFileInfo(fileName);
if(newFileInfo.exists())
QFile(fileName).remove();
nelements = imageStats.samples_per_channel * channels;
/* Create a new File, overwriting existing*/
if (fits_create_file(&new_fptr, fileName.toLocal8Bit(), &status))
{
fits_report_error(stderr, status);
return false;
}
int bitpix;
switch(imageStats.dataType)
{
case SEP_TBYTE:
bitpix = BYTE_IMG;
break;
case TSHORT:
bitpix = SHORT_IMG;
break;
case TUSHORT:
bitpix = USHORT_IMG;
break;
case TLONG:
bitpix = LONG_IMG;
break;
case TULONG:
bitpix = ULONG_IMG;
break;
case TFLOAT:
bitpix = FLOAT_IMG;
break;
case TDOUBLE:
bitpix = DOUBLE_IMG;
break;
default:
bitpix = BYTE_IMG;
}
fitsfile *fptr = new_fptr;
if (fits_create_img(fptr, bitpix, naxis, naxes, &status))
{
emit logOutput(QString("fits_create_img failed: %1").arg(error_status));
status = 0;
fits_flush_file(fptr, &status);
fits_close_file(fptr, &status);
return false;
}
/* Write Data */
if (fits_write_img(fptr, imageStats.dataType, 1, nelements, const_cast<void *>(reinterpret_cast<const void *>(imageBuffer)), &status))
{
fits_report_error(stderr, status);
return false;
}
// Copies all the headers except the first few, which CFITSIO writes automatically
for (int i = 0; i < records.count(); i++)
{
QString key = records[i].key;
QVariant value = records[i].value;
QString comment = records[i].comment;
// This should skip the first few headers, which CFITSIO will write anyway.
// So it avoids duplicating these headers.
// Note: the two standard COMMENT fields CFITSIO writes are handled below in the case-switch
if(key == "SIMPLE" ||
key == "BITPIX" ||
key.startsWith("NAXIS") ||
key == "EXTEND" ||
key == "BZERO" ||
key == "BSCALE")
continue;
switch (static_cast<QMetaType::Type>(value.userType()))
{
case QMetaType::Int:
{
int number = value.toInt();
fits_write_key(fptr, TINT, key.toLatin1().constData(), &number, comment.toLatin1().constData(), &status);
}
break;
case QMetaType::Double:
{
double number = value.toDouble();
fits_write_key(fptr, TDOUBLE, key.toLatin1().constData(), &number, comment.toLatin1().constData(), &status);
}
break;
case QMetaType::QString:
default:
{
if(key == "COMMENT" && (value.toString().contains("FITS (Flexible Image Transport System) format") ||
value.toString().contains("volume 376")))
{
// Don't duplicate the two standard comment fields CFITSIO writes to the file
}
else
{
if(key == "COMMENT")
{
fits_write_comment(fptr, comment.toLatin1().constData(), &status);
}
else if(key == "HISTORY")
{
fits_write_history(fptr, comment.toLatin1().constData(), &status);
}
else if(key.simplified() == "END")
{
// Don't write the end or the solution won't get written!
}
else
{
fits_write_key(fptr, TSTRING, key.toLatin1().constData(), value.toString().toLatin1().data(), comment.toLatin1().constData(), &status);
}
}
}
}
}
/* Write keywords */
//exposure = 1;
//fits_update_key(fptr, TLONG, "EXPOSURE", &exposure, "Total Exposure Time", &status);
// NAXIS1
if (fits_update_key(fptr, TUSHORT, "NAXIS1", &(imageStats.width), "length of data axis 1", &status))
{
fits_report_error(stderr, status);
return false;
}
// NAXIS2
if (fits_update_key(fptr, TUSHORT, "NAXIS2", &(imageStats.height), "length of data axis 2", &status))
{
fits_report_error(stderr, status);
return false;
}
if(hasSolution)
{
fits_update_key(fptr, TDOUBLE, "OBJCTRA", &solution.ra, "Object RA", &status);
fits_update_key(fptr, TDOUBLE, "OBJCTDEC", &solution.dec, "Object DEC", &status);
int epoch = 2000;
fits_update_key(fptr, TINT, "EQUINOX", &epoch, "Equinox", &status);
fits_update_key(fptr, TDOUBLE, "CRVAL1", &solution.ra, "CRVAL1", &status);
fits_update_key(fptr, TDOUBLE, "CRVAL2", &solution.dec, "CRVAL1", &status);
char radecsys[8] = "FK5";
char ctype1[16] = "RA---TAN";
char ctype2[16] = "DEC--TAN";
fits_update_key(fptr, TSTRING, "RADECSYS", radecsys, "RADECSYS", &status);
fits_update_key(fptr, TSTRING, "CTYPE1", ctype1, "CTYPE1", &status);
fits_update_key(fptr, TSTRING, "CTYPE2", ctype2, "CTYPE2", &status);
double crpix1 = imageStats.width / 2.0;
double crpix2 = imageStats.height / 2.0;
fits_update_key(fptr, TDOUBLE, "CRPIX1", &crpix1, "CRPIX1", &status);
fits_update_key(fptr, TDOUBLE, "CRPIX2", &crpix2, "CRPIX2", &status);
// Arcsecs per Pixel
double secpix1 = solution.parity == FITSImage::NEGATIVE ? solution.pixscale : -solution.pixscale;
double secpix2 = solution.pixscale;
fits_update_key(fptr, TDOUBLE, "SECPIX1", &secpix1, "SECPIX1", &status);
fits_update_key(fptr, TDOUBLE, "SECPIX2", &secpix2, "SECPIX2", &status);
double degpix1 = secpix1 / 3600.0;
double degpix2 = secpix2 / 3600.0;
fits_update_key(fptr, TDOUBLE, "CDELT1", °pix1, "CDELT1", &status);
fits_update_key(fptr, TDOUBLE, "CDELT2", °pix2, "CDELT2", &status);
// Rotation is CW, we need to convert it to CCW per CROTA1 definition
double rotation = 360 - solution.orientation;
if (rotation > 360)
rotation -= 360;
fits_update_key(fptr, TDOUBLE, "CROTA1", &rotation, "CROTA1", &status);
fits_update_key(fptr, TDOUBLE, "CROTA2", &rotation, "CROTA2", &status);
}
// ISO Date
if (fits_write_date(fptr, &status))
{
fits_report_error(stderr, status);
return false;
}
fits_flush_file(fptr, &status);
if(fits_close_file(fptr, &status))
{
emit logOutput(QString("Error closing file."));
return false;
}
emit logOutput("Saved FITS file:" + fileName);
return true;
}
//This method was copied and pasted from Fitsview in KStars
//It sets up the image that will be displayed on the screen
void fileio::generateQImage()
{
int sampling = 2;
// Account for leftover when sampling. Thus a 5-wide image sampled by 2
// would result in a width of 3 (samples 0, 2 and 4).
int w = (stats.width + sampling - 1) / sampling;
int h = (stats.height + sampling - 1) / sampling;
if (stats.channels == 1)
{
rawImage = QImage(w, h, QImage::Format_Indexed8);
rawImage.setColorCount(256);
for (int i = 0; i < 256; i++)
rawImage.setColor(i, qRgb(i, i, i));
}
else
{
rawImage = QImage(w, h, QImage::Format_RGB32);
}
Stretch stretch(static_cast<int>(stats.width),
static_cast<int>(stats.height),
stats.channels, static_cast<uint16_t>(stats.dataType));
// Compute new auto-stretch params.
StretchParams stretchParams = stretch.computeParams(m_ImageBuffer);
stretch.setParams(stretchParams);
stretch.run(m_ImageBuffer, &rawImage, sampling);
}
void fileio::logIssue(QString message){
if(logToSignal)
emit logOutput(message);
else
printf("%s", message.toUtf8().data());
}
uint8_t *fileio::getImageBuffer()
{
imageBufferTaken = true;
return m_ImageBuffer;
}
|