int
main (int argc, const char *argv[])
{
  GDALDriverH hDriver;
  double adfGeoTransform[6];
  GDALDatasetH in_Dataset;
  GDALDatasetH out_Dataset;
  double *data_scan_line;
  char *out_scan_line;
  int nBlockXSize, nBlockYSize;
  int bGotMin, bGotMax;
  int bands;
  int xsize;
  double lower_fiddle, upper_fiddle;
  double adfMinMax[2];
  /* These are hard coded for now - need to figure out a better way to handle this.. */
  double palette_in[256] =
    { 0.0, 1.00011, 1.9999649999999998, 3.000075, 3.9999299999999995, 5.00004,
    5.999895, 7.000005, 8.000115, 8.99997, 10.00008, 10.999935,
    12.000044999999998, 12.9999,
    14.00001, 15.00012, 15.999975, 17.000085000000002, 17.99994, 19.00005,
    19.999905000000002,
    21.000014999999998, 22.000125, 22.99998, 24.000089999999997, 24.999945,
    26.000055, 26.99991,
    28.00002, 28.999875000000003, 29.999985, 31.000094999999998, 31.99995,
    33.00006, 33.999915,
    35.000024999999994, 35.99988, 36.999990000000004, 38.0001, 38.999955,
    40.000065, 40.99992,
    42.000029999999995, 42.999885, 43.999995000000006, 45.000105, 45.99996,
    47.00007,
    47.999925000000005, 49.000035, 49.99989, 51.0, 52.00011, 52.999965,
    54.000075, 54.99993,
    56.00004, 56.999895, 58.000004999999994, 59.000115, 59.99997,
    61.000080000000004, 61.999935,
    63.000045, 63.9999, 65.00001, 66.00012, 66.999975, 68.000085, 68.99994,
    70.00004999999999,
    70.999905, 72.000015, 73.000125, 73.99998000000001, 75.00009, 75.999945,
    77.00005499999999,
    77.99991, 79.00002, 79.99987499999999, 80.99998500000001, 82.000095,
    82.99995,
    84.00005999999999, 84.999915, 86.00002500000001, 86.99987999999999,
    87.99999000000001, 89.0001,
    89.999955, 91.00006499999999, 91.99992, 93.00003, 93.99988499999999,
    94.999995, 96.000105,
    96.99996, 98.00007, 98.999925, 100.000035, 100.99989, 102.0, 103.00011,
    103.999965, 105.000075,
    105.99993, 107.00004, 107.999895, 109.000005, 110.00011500000001,
    110.99997, 112.00008,
    112.99993500000001, 114.000045, 114.9999, 116.00000999999999, 117.00012,
    117.999975,
    119.000085, 119.99994, 121.00005, 121.999905, 123.00001499999999,
    124.000125,
    124.99998000000001, 126.00009, 126.999945, 128.000055, 128.99991,
    130.00002, 130.999875,
    131.99998499999998, 133.000095, 133.99995, 135.00006, 135.999915,
    137.00002500000002,
    137.99988, 138.99999, 140.00009999999997, 140.999955, 142.000065,
    142.99991999999997,
    144.00003, 144.999885, 145.99999499999998, 147.000105, 147.99996000000002,
    149.00007,
    149.999925, 151.00003500000003, 151.99989, 153.0, 154.00010999999998,
    154.999965, 156.000075,
    156.99992999999998, 158.00004, 158.999895, 160.000005, 161.000115,
    161.99997000000002,
    163.00008, 163.999935, 165.000045, 165.9999, 167.00001,
    168.00011999999998, 168.999975,
    170.000085, 170.99993999999998, 172.00005000000002, 172.999905,
    174.000015, 175.000125,
    175.99998000000002, 177.00009, 177.999945, 179.00005499999997, 179.99991,
    181.00002,
    181.999875, 182.999985, 184.00009500000002, 184.99994999999998, 186.00006,
    186.99991500000002,
    188.000025, 188.99988, 189.99999, 191.0001, 191.999955,
    193.00006499999998, 193.99992,
    195.00003, 195.99988499999998, 196.999995, 198.00010500000002, 198.99996,
    200.00007,
    200.99992500000002, 202.000035, 202.99989, 204.0, 205.00011, 205.999965,
    207.00007499999998,
    207.99993, 209.00004, 209.99989499999998, 211.00000500000002, 212.000115,
    212.99997, 214.00008,
    214.999935, 216.000045, 216.9999, 218.00001, 219.00012, 219.999975,
    221.00008499999998,
    221.99994, 223.00005000000002, 223.99990499999998, 225.00001500000002,
    226.000125, 226.99998,
    228.00009, 228.999945, 230.000055, 230.99991, 232.00001999999998,
    232.999875, 233.999985,
    235.000095, 235.99995, 237.00006, 237.999915, 239.000025, 239.99988,
    240.99999, 242.0001,
    242.999955, 244.000065, 244.99992, 246.00002999999998, 246.999885,
    247.999995, 249.000105,
    249.99996000000002, 251.00007, 251.999925, 253.000035, 253.99989, 255.0
  };
  double palette_out[256] =
    { 0.0, 0.042075, 0.08415, 0.126225, 0.169065, 0.21216, 0.255765, 0.29988,
    0.345015, 0.390915, 0.437835, 0.48602999999999996, 0.5352450000000001,
    0.58599, 0.63801,
    0.69156, 0.7468950000000001, 0.804015, 0.8629199999999999,
    0.9238649999999999, 0.98685, 1.05213,
    1.119705, 1.18983, 1.26225, 1.337475, 1.415505, 1.49634, 1.580235,
    1.6674449999999998, 1.75746,
    1.851045, 1.9482, 2.04867, 2.152965, 2.2608300000000003,
    2.3727750000000003, 2.4885450000000002,
    2.6083950000000002, 2.73258, 2.8611000000000004, 2.993955,
    3.1313999999999997, 3.27369, 3.42057,
    3.572295, 3.72912, 3.891045, 4.05807, 4.23045, 4.408440000000001,
    4.591785, 4.780995, 4.975815,
    5.1765, 5.38305, 5.595975, 5.8150200000000005, 6.040185, 6.27198,
    6.510405, 6.755205, 7.007145,
    7.265715, 7.53117, 7.8040199999999995, 8.084010000000001, 8.37114,
    8.66592, 8.968095, 9.27792,
    9.59565, 9.92103, 10.25457, 10.596015, 10.945875, 11.30415, 11.670585,
    12.04569, 12.429465,
    12.82191, 13.223279999999999, 13.63383, 14.053305, 14.48196,
    14.919794999999999, 15.36732,
    15.82428, 16.29093, 16.767270000000003, 17.253555, 17.749785, 18.256215,
    18.925845,
    19.456245000000003, 19.99863, 20.552745, 21.11859, 21.696165, 22.285725,
    22.887014999999998,
    23.500035, 24.125295, 24.762285, 25.411260000000002, 26.071965, 26.74491,
    27.42984, 28.12701,
    28.835910000000002, 29.55705, 30.29043, 31.035795, 31.7934, 32.56299,
    33.345075, 34.139145,
    34.94571, 35.764514999999996, 36.595305, 37.438845, 38.294625, 39.162645,
    40.04316, 40.935915,
    41.84142, 42.759165, 43.68966, 44.632394999999995, 45.58788, 46.55586,
    47.536335,
    48.529560000000004, 49.535535, 50.554005000000004, 51.58497, 52.62894,
    53.68566, 54.75513,
    55.837095, 56.932064999999994, 58.040040000000005, 59.160765,
    60.294239999999995, 61.44072,
    62.59995000000001, 63.772439999999996, 64.95768000000001,
    66.15592500000001, 67.36743,
    68.591685, 69.82919999999999, 71.07972, 72.343245, 73.620285, 74.910075,
    76.21337999999999,
    77.52968999999999, 78.85926, 80.20209, 81.55843499999999, 82.927785,
    84.31065, 85.66419,
    87.10264500000001, 88.611225, 90.18712500000001, 91.82779500000001,
    93.52992, 95.291205,
    97.108845, 98.979525, 100.90095, 102.87006, 104.884305, 106.94037,
    109.03596, 111.16827,
    113.33424000000001, 115.531065, 117.756195, 120.00657, 122.27964,
    124.572345,
    126.88213499999999, 129.20595, 131.54124, 133.8852, 136.23477,
    138.58714500000002, 140.939775,
    143.289855, 145.63458, 147.97089, 150.296235, 152.60781, 154.902555,
    157.17817499999998,
    159.431355, 161.65929, 163.859685, 166.02948, 168.165615, 170.26554,
    172.32645, 174.34554,
    176.320005, 178.24704, 180.292905, 182.130945, 183.953685, 185.76138,
    187.554285, 189.33291,
    191.09751, 192.84834, 194.58591, 196.310475, 198.02229, 199.72161,
    201.4092, 203.084805,
    204.74944499999998, 206.402865, 208.04557499999999, 209.67808499999998,
    211.30065, 212.913525,
    214.516965, 216.11148, 217.69758000000002, 219.27501, 220.84479,
    222.406665, 223.9614,
    225.50924999999998, 227.05047000000002, 228.585315, 230.114295,
    231.63766500000003,
    233.15568000000002, 234.66885000000002, 236.17743, 237.681675, 239.18184,
    240.67869, 242.172225,
    243.66295499999998, 245.15088, 246.636765, 248.12061000000003, 249.602925,
    251.083965,
    252.56424, 254.04375, 255.0
  };


  GDALAllRegister ();


  /* ussage.. */
  if (argc != 3)
    ussage ();

  /* Set cache to something reasonable.. - 1/2 gig */
  CPLSetConfigOption ("GDAL_CACHEMAX", "512");

  /* open datasets.. */
  in_Dataset = GDAL_open_read (argv[1]);
  out_Dataset = make_me_a_sandwitch (&in_Dataset, argv[2]);

  /* Basic info on source dataset.. */
  GDALGetBlockSize (GDALGetRasterBand (in_Dataset, 1), &nBlockXSize,
		    &nBlockYSize);
  printf ("Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize,
	  GDALGetDataTypeName (GDALGetRasterDataType
			       (GDALGetRasterBand (in_Dataset, 1))),
	  GDALGetColorInterpretationName (GDALGetRasterColorInterpretation
					  (GDALGetRasterBand
					   (in_Dataset, 1))));

  /* Loop though bands, scaling the data.. */
  xsize = GDALGetRasterXSize (in_Dataset);
  data_scan_line = (double *) CPLMalloc (sizeof (double) * xsize);
  out_scan_line = (char *) CPLMalloc (sizeof (char) * xsize);

  for (bands = 1; bands <= GDALGetRasterCount (in_Dataset); bands++)
    {
      int x;
      double min = 9999999.0, max = 0.0;	/* probibly a better way to set these.. */
      double dmin, dmax, middle;
      GDALRasterBandH data_band, out_band;
      int y_index = 0;
      data_band = GDALGetRasterBand (in_Dataset, bands);
      out_band = GDALGetRasterBand (out_Dataset, bands);

      /* Set nodata for that band */
      GDALSetRasterNoDataValue (out_band, 0.0);

      /*Find Min,Max, required for scaling */
      for (y_index = 0; y_index < GDALGetRasterYSize (in_Dataset); y_index++)
	{
	  /* Read data.. */
	  GDALRasterIO (data_band, GF_Read, 0, y_index, xsize, 1,
			data_scan_line, xsize, 1, GDT_Float64, 0, 0);
	  for (x = 0; x < xsize; x++)
	    {
	      if (data_scan_line[x] < MAX_MODIS
		  && data_scan_line[x] > MIN_VALUE)
		{
		  if (data_scan_line[x] > max)
		    max = data_scan_line[x];
		  else if (data_scan_line[x] < min)
		    min = data_scan_line[x];
		}
	    }
	}

      dmax = (double) max;
      dmin = (double) min;

      printf ("Info: For Band %d -> Min=%g,Max=%g\n", bands, dmin, dmax);

      for (y_index = 0; y_index < GDALGetRasterYSize (in_Dataset); y_index++)
	{
	  double scaled;

	  /* Read data.. */
	  GDALRasterIO (data_band, GF_Read, 0, y_index, xsize, 1,
			data_scan_line, xsize, 1, GDT_Float64, 0, 0);

	  /* scale each .. */
	  for (x = 0; x < xsize; x++)
	    {
	      out_scan_line[x] =
		scale (palette_in, palette_out, data_scan_line[x], dmin,
		       dmax);
	    }

	  /* now write out band.. */
	  GDALRasterIO (out_band, GF_Write, 0, y_index, xsize, 1,
			out_scan_line, xsize, 1, GDT_Byte, 0, 0);
	}

    }


  /* close file, and we are done. */
  GDALClose (out_Dataset);

}
示例#2
0
HRESULT CImage::Open(char* pszPathName,UINT uMode)
{
	Close();

	m_pszPathName=new char[strlen(pszPathName)+1];
	strcpy(m_pszPathName,pszPathName);

	if(strcmp(m_pszPathName+strlen(m_pszPathName)-3,"txt")==0)
	{
		char szPath[512];
		memset(szPath,0,512*sizeof(char));

		int nPos=-1;
		int i=strlen(m_pszPathName)-1;
		for(;i>=0;i--)
		{
			if(m_pszPathName[i]=='\\'||m_pszPathName[i]=='/')
			{
				nPos=i;
				break;
			}
		}
		for(i=0;i<=nPos;i++)
		{
			szPath[i]=m_pszPathName[i];
		}

		FILE* fp=fopen(m_pszPathName,"rt");
		if(fp==NULL)
		{
			return S_FALSE;
		}
		BOOL bGeoCoded=FALSE;
		char szBuffer[1024];
		char szTag[100],szEqualMark[10],szValue[512];
		while(!feof(fp))
		{
			memset(szBuffer, 0 ,sizeof(char)*1024);
			memset(szTag, 0 ,sizeof(char)*100);
			memset(szEqualMark, 0 ,sizeof(char)*10);
			memset(szValue, 0 ,sizeof(char)*512);
			
			fgets(szBuffer,1023,fp);
		
			sscanf(szBuffer,"%s%s%s",szTag,szEqualMark,szValue);
			int nLength=strlen(szValue);
			if(nLength>0)
			{
				if(szValue[nLength-1]==';')
				{
					szValue[nLength-1]='\0';
				}
			}
			// Parse the satellite ID from the GC report file. [Wei.Zuo,4/15/2009]
			if(strcmp(szTag,"satelliteID")==0)
			{
				if(strcmp(szValue,"\"HJ1A\"")==0)
					m_nSatelliteID = 1;
				else if(strcmp(szValue,"\"HJ1B\"")==0)
					m_nSatelliteID = 2;
				else 
					m_nSatelliteID = 0;
			}
			else if(strcmp(szTag,"sensorID")==0)
			{
				if(strcmp(szValue,"\"CCD\"")==0)
				{
					m_nSensorType=SENSOR_CCD;
					m_nBPB=1;
					m_datatype=ConvertDataType2GDALDataType(Pixel_Byte);
				}
				else if(strcmp(szValue,"\"HSI\"")==0)
				{
					m_nSensorType=SENSOR_HSI;
					m_nBPB=2;
					m_datatype=ConvertDataType2GDALDataType(Pixel_Int16);
				}
				else if(strcmp(szValue,"\"IRS\"")==0)
				{
					m_nSensorType=SENSOR_IRS;
					m_nBPB=2;
					m_datatype=ConvertDataType2GDALDataType(Pixel_Int16);
				}
				// Add sensor CCD1 and CCD2. [Wei.Zuo,4/15/2009]
				else if(strcmp(szValue,"\"CCD1\"")==0)
				{
					m_nSensorType=SENSOR_CCD1;
					m_nBPB=1;
					m_datatype=ConvertDataType2GDALDataType(Pixel_Byte);
				}
				else if(strcmp(szValue,"\"CCD2\"")==0)
				{
					m_nSensorType=SENSOR_CCD2;
					m_nBPB=1;
					m_datatype=ConvertDataType2GDALDataType(Pixel_Byte);
				}
				// Later will add sensor SAR. [Wei.Zuo,4/15/2009]
			}
			else if(strcmp(szTag,"ImgNum")==0)
			{
				m_nImgNum=atoi(szValue);
				m_nBandNum=m_nImgNum;
			}
			else if(strcmp(szTag,"Bands")==0)
			{
				m_nBandNum=atoi(szValue);
			}
			else if(strcmp(szTag,"processedImageWidth")==0)
			{
				m_nCols=atoi(szValue);
			}
			else if(strcmp(szTag,"processedImageHeight")==0)
			{
				m_nRows=atoi(szValue);
			}
			//������Ϣ
			else if(strcmp(szTag,"pixelSpacing")==0)
			{
				m_CellSize=atof(szValue);

				bGeoCoded=TRUE;
			}
			else if(strcmp(szTag,"productLowerLeftX")==0)
			{
				m_LBX=atof(szValue);
			}
			else if(strcmp(szTag,"productLowerLeftY")==0)
			{
				m_LBY=atof(szValue);
			}
			else if(strcmp(szTag,"productLowerRightX")==0)
			{
				
			}
			else if(strcmp(szTag,"productLowerRightY")==0)
			{
				
			}
			else if(strcmp(szTag,"productUpperRightX")==0)
			{
				m_RTX=atof(szValue);
			}
			else if(strcmp(szTag,"productUpperRightY")==0)
			{
				m_RTY=atof(szValue);
			}
			else if(strcmp(szTag,"productUpperLeftX")==0)
			{
				
			}
			else if(strcmp(szTag,"productUpperLeftY")==0)
			{
				
			}
		}
		if(m_nBandNum<=0||m_nImgNum<=0)
		{
			fclose(fp);

			return S_FALSE;
		}

		if(bGeoCoded==FALSE)
		{
			m_LBX=0;
			m_LBY=0;
			m_RTX=m_nCols;
			m_RTY=m_nRows;
			m_CellSize=1.0;
		}

		m_fpRaws=new FILE*[m_nImgNum];
		memset(m_fpRaws,0,sizeof(FILE*)*m_nImgNum);

		for(i=0;i<m_nImgNum;i++)
		{
			char szStdTag[100];
			sprintf(szStdTag,"outputdata%d",i);

			fseek(fp,0,SEEK_SET);
			while(!feof(fp))
			{
				fgets(szBuffer,1023,fp);
			
				sscanf(szBuffer,"%s%s%s",szTag,szEqualMark,szValue);
				if(strcmp(szTag,szStdTag)==0)
				{
					char szName[512];
					memset(szName,0,512*sizeof(char));

					int nPos=-1;
					int k=strlen(szValue)-1;
					for(;k>=0;k--)
					{
						if(szValue[k]=='\\'||szValue[k]=='/')
						{
							nPos=k;
							break;
						}
					}
					for(k=nPos+1;k<((int)(strlen(szValue)));k++)
					{
						if(szValue[k]=='\"')
						{
							break;
						}
						szName[k-nPos-1]=szValue[k];
					}
					
					char szRawPathName[512];
					strcpy(szRawPathName,szPath);
					strcat(szRawPathName,szName);

					if(m_nSensorType==SENSOR_IRS&&i==3&&m_nRows==4500&&m_nCols==4500)
					{
						char szRawPathNameTemp[512];
						sprintf(szRawPathNameTemp,"%s_resample.raw",szRawPathName);
						
						FILE* fpSrc=fopen(szRawPathName,"rb");
						FILE* fpDst=fopen(szRawPathNameTemp,"wb");
						if(fpSrc==NULL||fpDst==NULL)
						{
							Close();
							fclose(fpSrc);
							fclose(fpDst);
							return S_FALSE;
						}
						BYTE* pSrcBuffer=new BYTE[m_nCols/2*m_nBPB];
						BYTE* pDstBuffer=new BYTE[m_nCols*m_nBPB];
						int m=0,n=0;
						for(m=0;m<m_nRows/2;m++)
						{
							fread(pSrcBuffer,m_nBPB,m_nCols/2,fpSrc);
							for(n=0;n<m_nCols/2;n++)
							{
								memcpy(pDstBuffer+(n*2+0)*m_nBPB,pSrcBuffer+n*m_nBPB,m_nBPB);
								memcpy(pDstBuffer+(n*2+1)*m_nBPB,pSrcBuffer+n*m_nBPB,m_nBPB);
							}
							fwrite(pDstBuffer,m_nBPB,m_nCols,fpDst);
							fwrite(pDstBuffer,m_nBPB,m_nCols,fpDst);
						}
						fclose(fpSrc);
						fclose(fpDst);

						delete [] pSrcBuffer;
						delete [] pDstBuffer;

						strcpy(szRawPathName,szRawPathNameTemp);
					}

					m_fpRaws[i]=fopen(szRawPathName,"rb");
					if(m_fpRaws[i]==NULL)
					{
						Close();
						fclose(fp);
						return S_FALSE;
					}
				}
			}
		}

		fclose(fp);
	}
	else
	{
		GDALAllRegister();
		m_pGdalImage=(GDALDataset*)GDALOpen(m_pszPathName,GA_ReadOnly);

		if(m_pGdalImage==NULL)
		{
			return S_FALSE;
		}
		//��ȡӰ��ߴ���Ϣ
		m_nCols=GDALGetRasterXSize(m_pGdalImage);
		m_nRows=GDALGetRasterYSize(m_pGdalImage);
		m_nBandNum=GDALGetRasterCount(m_pGdalImage);
		if(m_nBandNum<=0)
		{
			return S_FALSE;
		}
		m_datatype=GDALGetRasterDataType(GDALGetRasterBand(m_pGdalImage,1));
		m_nBPB=GDALGetDataTypeSize(m_datatype)/8;
		for(int i=2;i<=m_nBandNum;i++)
		{
			if(GDALGetRasterDataType(GDALGetRasterBand(m_pGdalImage,i))!=m_datatype)
			{
				GDALClose(m_pGdalImage);
				COutput::OutputFileOpenFailed(m_pszPathName);

				return S_FALSE;
			}
		}
		//��ȡ������Ϣ
		double grdTransform[6];
		memset(grdTransform,0,sizeof(double)*6);
		CPLErr error=m_pGdalImage->GetGeoTransform(grdTransform);
		if(error==CE_None)
		{
			double X0,Y0,X2,Y2;
			X0=grdTransform[0];
			Y0=grdTransform[3];
			X2=grdTransform[0]+m_nCols*grdTransform[1]+m_nRows*grdTransform[2];
			Y2=grdTransform[3]+m_nCols*grdTransform[4]+m_nRows*grdTransform[5];

			m_LBX=__min(X0,X2);
			m_LBY=__min(Y0,Y2);
			m_RTX=__max(X0,X2);
			m_RTY=__max(Y0,Y2);
			m_CellSize=fabs(grdTransform[1]);
		}
		else
		{
			m_LBX=0;
			m_LBY=0;
			m_RTX=m_nCols;
			m_RTY=m_nRows;
			m_CellSize=1.0;
		}
	}

	//��ʼ��������
	m_nCacheRow=m_CacheSize/(m_nCols*m_nBandNum*m_nBPB);
	if(m_nCacheRow<=0)
	{
		if(m_pCache)
		{
			delete [] m_pCache;
		}
		m_pCache=NULL;
		BOOL bMemEnough=FALSE;
		int nRow=24000;
		while(bMemEnough==FALSE&&nRow>1)
		{
			try
			{
				m_nCacheRow=nRow;
				m_CacheSize=m_nCols*m_nBandNum*m_nBPB*m_nCacheRow;
				m_pCache=new BYTE[m_CacheSize];
				bMemEnough=TRUE;
			}
			catch(...)
			{
				nRow=nRow/2;
				if(nRow<=0)
				{
					nRow=1;
				}
			}
		}
		if(m_pCache==NULL)
		{
			try
			{
				m_pCache=new BYTE[m_nCols*m_nBandNum*m_nBPB*1];
				m_CacheSize=m_nCols*m_nBandNum*m_nBPB*1;
				m_nCacheRow=1;
			}
			catch(...)
			{
				COutput::OutputMemoryError();
				Close();
				return S_FALSE;
			}
		}
	}

	if((uMode&modeAqlut)==modeAqlut)
	{
		//here pHistogram mast write as follows
		CHistogram* pHistogram=new CHistogram[m_nBandNum];
		for(int i=0;i<m_nBandNum;i++)
		{
			pHistogram[i].StatHistogram(this,i);
		}
		m_pHistogram=pHistogram;
		pHistogram=NULL;
	}
	
	return S_OK;
}
示例#3
0
std::shared_ptr<toprsImg> toprsGadlReader::getTileBlockRead( const toprsIRect& tileRect,int resLevel )
{
	std::shared_ptr<toprsImg> result;
	toprsIRect imageBound = getBoundingRect(resLevel);
	theTile->setImgRect(tileRect);

	// Compute clip rectangle with respect to the image bounds.
	toprsIRect clipRect   = tileRect.clipToRect(imageBound);

	if (tileRect.completely_within(clipRect) == false)
	{
		// Not filling whole tile so blank it out first.
		theTile->makeBlank();
	}
	if(m_isBlocked)
	{
		int xSize=0, ySize=0;
		GDALGetBlockSize(resolveRasterBand( resLevel, 1 ),
			&xSize,
			&ySize);
		toprsIRect blockRect = clipRect;
		blockRect.stretchToTileBoundary(toprsIpt(xSize, ySize));
		blockRect = blockRect.clipToRect(getBoundingRect(resLevel));

		// we need to cache here
		//
		toprs_int64 x = blockRect.left_up().x;
		toprs_int64 y = blockRect.left_up().y;
		toprs_int64 maxx = blockRect.right_down().x;
		toprs_int64 maxy = blockRect.right_down().y;
		toprs_uint32 aGdalBandIndex   = 1;
		toprs_uint32 rasterCount = GDALGetRasterCount(theDataset);
		if (m_outputBandList.size() > 0)
		{
			rasterCount = m_outputBandList.size();
		}

		toprs_uint32 outputBandIndex = 0;
		for(;x < maxx;x+=xSize)
		{
			for(;y < maxy;y+=ySize)
			{
				toprsIpt origin(x,y);

				//std::shared_ptr<toprsImg> cacheTile = toprsAppFixedTileCache::instance()->getTile(m_rlevelBlockCache[resLevel], origin);//xizhi

				//if(!cacheTile.valid())
				//{
				//	toprsIRect rect(origin.x,origin.y,origin.x+xSize-1, origin.y+ySize-1);
				//	theSingleBandTile->setImgRect(rect);
				//	toprsIRect validRect = rect.clipToRect(imageBound);
				//	cacheTile = toprsImgFactory::instance()->create(this);
				//	cacheTile->setImgRect(validRect);
				//	cacheTile->initialize();                          
				//	for(toprs_uint32 aBandIndex =1; aBandIndex <= rasterCount; ++aBandIndex)
				//	{
				//		if (m_outputBandList.size() > 0)
				//		{
				//			aGdalBandIndex = m_outputBandList[outputBandIndex] + 1;
				//			outputBandIndex++;
				//		}
				//		else
				//		{
				//			aGdalBandIndex = aBandIndex;
				//		}
				//		GDALRasterBandH aBand = resolveRasterBand( resLevel, aGdalBandIndex );
				//		if ( aBand )
				//		{
				//			try{

				//				bool bReadSuccess =  (GDALReadBlock(aBand, x/xSize, y/ySize, theSingleBandTile->getBuf() )== CE_None) ? true : false;
				//				if(bReadSuccess)
				//				{
				//					//cacheTile->loadBand(theSingleBandTile->getBuf(), theSingleBandTile->getImgRect(), aBandIndex-1);
				//				}
				//			}
				//			catch(...)
				//			{
				//			}
				//		}
				//	}
				//	//cacheTile->validate();
				//	//toprsAppFixedTileCache::instance()->addTile(m_rlevelBlockCache[resLevel], cacheTile.get(), false);
				//}
				//theTile->loadTile(cacheTile->getBuf(), cacheTile->getImageRectangle(), TOPRS_BSQ);
				result = theTile;
			}
		}
	}
	if(result) result->validate();

	return result;
}
示例#4
0
int QgsZonalStatistics::calculateStatistics( QProgressDialog* p )
{
  if ( !mPolygonLayer || mPolygonLayer->geometryType() != QGis::Polygon )
  {
    return 1;
  }

  QgsVectorDataProvider* vectorProvider = mPolygonLayer->dataProvider();
  if ( !vectorProvider )
  {
    return 2;
  }

  //open the raster layer and the raster band
  GDALAllRegister();
  GDALDatasetH inputDataset = GDALOpen( TO8F( mRasterFilePath ), GA_ReadOnly );
  if ( inputDataset == NULL )
  {
    return 3;
  }

  if ( GDALGetRasterCount( inputDataset ) < ( mRasterBand - 1 ) )
  {
    GDALClose( inputDataset );
    return 4;
  }

  GDALRasterBandH rasterBand = GDALGetRasterBand( inputDataset, mRasterBand );
  if ( rasterBand == NULL )
  {
    GDALClose( inputDataset );
    return 5;
  }
  mInputNodataValue = GDALGetRasterNoDataValue( rasterBand, NULL );

  //get geometry info about raster layer
  int nCellsXGDAL = GDALGetRasterXSize( inputDataset );
  int nCellsYGDAL = GDALGetRasterYSize( inputDataset );
  double geoTransform[6];
  if ( GDALGetGeoTransform( inputDataset, geoTransform ) != CE_None )
  {
    GDALClose( inputDataset );
    return 6;
  }
  double cellsizeX = geoTransform[1];
  if ( cellsizeX < 0 )
  {
    cellsizeX = -cellsizeX;
  }
  double cellsizeY = geoTransform[5];
  if ( cellsizeY < 0 )
  {
    cellsizeY = -cellsizeY;
  }
  QgsRectangle rasterBBox( geoTransform[0], geoTransform[3] - ( nCellsYGDAL * cellsizeY ),
                           geoTransform[0] + ( nCellsXGDAL * cellsizeX ), geoTransform[3] );

  //add the new count, sum, mean fields to the provider
  QList<QgsField> newFieldList;
  QString countFieldName = getUniqueFieldName( mAttributePrefix + "count" );
  QString sumFieldName = getUniqueFieldName( mAttributePrefix + "sum" );
  QString meanFieldName = getUniqueFieldName( mAttributePrefix + "mean" );
  QgsField countField( countFieldName, QVariant::Double, "double precision" );
  QgsField sumField( sumFieldName, QVariant::Double, "double precision" );
  QgsField meanField( meanFieldName, QVariant::Double, "double precision" );
  newFieldList.push_back( countField );
  newFieldList.push_back( sumField );
  newFieldList.push_back( meanField );
  vectorProvider->addAttributes( newFieldList );

  //index of the new fields
  int countIndex = vectorProvider->fieldNameIndex( countFieldName );
  int sumIndex = vectorProvider->fieldNameIndex( sumFieldName );
  int meanIndex = vectorProvider->fieldNameIndex( meanFieldName );

  if ( countIndex == -1 || sumIndex == -1 || meanIndex == -1 )
  {
    return 8;
  }

  //progress dialog
  long featureCount = vectorProvider->featureCount();
  if ( p )
  {
    p->setMaximum( featureCount );
  }


  //iterate over each polygon
  QgsFeatureRequest request;
  request.setSubsetOfAttributes( QgsAttributeList() );
  QgsFeatureIterator fi = vectorProvider->getFeatures( request );
  QgsFeature f;
  double count = 0;
  double sum = 0;
  double mean = 0;
  int featureCounter = 0;

  while ( fi.nextFeature( f ) )
  {
    if ( p )
    {
      p->setValue( featureCounter );
    }

    if ( p && p->wasCanceled() )
    {
      break;
    }

    QgsGeometry* featureGeometry = f.geometry();
    if ( !featureGeometry )
    {
      ++featureCounter;
      continue;
    }

    QgsRectangle featureRect = featureGeometry->boundingBox().intersect( &rasterBBox );
    if ( featureRect.isEmpty() )
    {
      ++featureCounter;
      continue;
    }

    int offsetX, offsetY, nCellsX, nCellsY;
    if ( cellInfoForBBox( rasterBBox, featureRect, cellsizeX, cellsizeY, offsetX, offsetY, nCellsX, nCellsY ) != 0 )
    {
      ++featureCounter;
      continue;
    }

    //avoid access to cells outside of the raster (may occur because of rounding)
    if (( offsetX + nCellsX ) > nCellsXGDAL )
    {
      nCellsX = nCellsXGDAL - offsetX;
    }
    if (( offsetY + nCellsY ) > nCellsYGDAL )
    {
      nCellsY = nCellsYGDAL - offsetY;
    }

    statisticsFromMiddlePointTest( rasterBand, featureGeometry, offsetX, offsetY, nCellsX, nCellsY, cellsizeX, cellsizeY,
                                   rasterBBox, sum, count );

    if ( count <= 1 )
    {
      //the cell resolution is probably larger than the polygon area. We switch to precise pixel - polygon intersection in this case
      statisticsFromPreciseIntersection( rasterBand, featureGeometry, offsetX, offsetY, nCellsX, nCellsY, cellsizeX, cellsizeY,
                                         rasterBBox, sum, count );
    }


    if ( count == 0 )
    {
      mean = 0;
    }
    else
    {
      mean = sum / count;
    }

    //write the statistics value to the vector data provider
    QgsChangedAttributesMap changeMap;
    QgsAttributeMap changeAttributeMap;
    changeAttributeMap.insert( countIndex, QVariant( count ) );
    changeAttributeMap.insert( sumIndex, QVariant( sum ) );
    changeAttributeMap.insert( meanIndex, QVariant( mean ) );
    changeMap.insert( f.id(), changeAttributeMap );
    vectorProvider->changeAttributeValues( changeMap );

    ++featureCounter;
  }

  if ( p )
  {
    p->setValue( featureCount );
  }

  GDALClose( inputDataset );
  mPolygonLayer->updateFields();

  if ( p && p->wasCanceled() )
  {
    return 9;
  }

  return 0;
}
示例#5
0
void toprsGadlReader::populateLut()
{
	theLut.reset(); // toprsRefPtr not a leak.
	if(isIndexed(1)&&theDataset)
	{
		GDALColorTableH aTable = GDALGetRasterColorTable(GDALGetRasterBand( theDataset, 1 ));
		GDALPaletteInterp interp = GDALGetPaletteInterpretation(aTable);
		if(aTable && ( (interp == GPI_Gray) || (interp == GPI_RGB)))
		{
			GDALColorEntry colorEntry;
			int numberOfElements = GDALGetColorEntryCount(aTable);
			int idx = 0;
			if(numberOfElements)
			{
				// GPI_Gray Grayscale (in GDALColorEntry.c1)
				// GPI_RGB Red, Green, Blue and Alpha in (in c1, c2, c3 and c4)
				theLut.reset(new toprsNBandLutDataObject(numberOfElements,4,TOPRS_UINT8,-1));
				bool nullSet = false;
				for(idx = 0; idx < numberOfElements; ++idx)
				{
					switch(interp)
					{
					case GPI_RGB:
						{
							if(GDALGetColorEntryAsRGB(aTable, idx, &colorEntry))
							{
								(*theLut)[idx][0] = colorEntry.c1;
								(*theLut)[idx][1] = colorEntry.c2;
								(*theLut)[idx][2] = colorEntry.c3;
								(*theLut)[idx][3] = colorEntry.c4;

								if ( !nullSet )
								{
									if ( m_preservePaletteIndexesFlag )
									{
										// If preserving palette set the null to the fix alpha of 0.
										if ( (*theLut)[idx][3] == 0 )
										{
											theLut->setNullPixelIndex(idx);
											nullSet = true;
										}
									}
									else
									{
										//---
										// Not using alpha.
										// Since the alpha is currently not used, look for the null
										// pixel index and set if we find. If at some point the alpha
										// is taken out this can be removed.
										//---
										if ( ( (*theLut)[idx][0] == 0 ) &&
											( (*theLut)[idx][1] == 0 ) &&
											( (*theLut)[idx][2] == 0 ) )
										{
											theLut->setNullPixelIndex(idx);
											nullSet = true;
										}
									}
								}
							}
							else
							{
								(*theLut)[idx][0] = 0;
								(*theLut)[idx][1] = 0;
								(*theLut)[idx][2] = 0;
								(*theLut)[idx][3] = 0;

								// Look for the null pixel index and set if we find.
								if ( !nullSet )
								{
									if ( (*theLut)[idx][0] == 0 )
									{
										theLut->setNullPixelIndex(idx);
									}
								}
							}
							break;
						}
					case GPI_Gray:
						{
							const GDALColorEntry* constEntry =  GDALGetColorEntry(aTable, idx);
							if(constEntry)
							{
								(*theLut)[idx][0] = constEntry->c1;
							}
							else
							{
								(*theLut)[idx][0] = 0;
							}
							break;
						}
					default:
						{
							break;
						}
					}
				}
			}
		}

		toprs_uint32 rasterCount = GDALGetRasterCount(theDataset);
		for(toprs_uint32 aGdalBandIndex=1; aGdalBandIndex <= rasterCount; ++aGdalBandIndex)
		{
			GDALRasterBandH aBand = GDALGetRasterBand( theDataset, aGdalBandIndex );
			if (aBand)
			{
				GDALRasterAttributeTableH hRAT = GDALGetDefaultRAT(aBand);
				int colCount = GDALRATGetColumnCount(hRAT);
				for (toprs_int32 col = 0; col < colCount; col++)
				{
					const char* colName = GDALRATGetNameOfCol(hRAT, col);
					if (colName)
					{
						if (strcmp(colName, "Class_Names") == 0)
						{
							std::vector<std::string> entryLabels;
							toprs_int32 rowCount = GDALRATGetRowCount(hRAT);
							for (toprs_int32 row = 0; row < rowCount; row++)
							{
								const char* className = GDALRATGetValueAsString(hRAT, row, col);
								std::string entryLabel(className);
								entryLabels.push_back(entryLabel);
							}
							theLut->setEntryLables(aGdalBandIndex-1, entryLabels);
						}
					}
				}
			}
		}
	}
}
示例#6
0
bool toprsGadlReader::open()
{
	if(isOpen())
	{
		close();
	}
	std::string driverNameTmp;

	if (theSubDatasets.size() == 0)
	{
		// Note:  Cannot feed GDALOpen a NULL string!
		if (theImageFile.size())
		{
			theDataset = GDALOpen(theImageFile.c_str(), GA_ReadOnly); 
			if( theDataset == 0 )
			{
				return false;
			}
		}
		else
		{
			return false;
		}


		// Check if it is nitf data for deciding whether or not open each sub-dataset
		//This will be removed eventually when toprs can handle 2GB nitf file.
		GDALDriverH driverTmp = GDALGetDatasetDriver(theDataset);
		bool isNtif = false;
		if (driverTmp != 0)
		{
			driverNameTmp = std::string(GDALGetDriverShortName(driverTmp));
			std::transform(driverNameTmp.begin(), driverNameTmp.end(), driverNameTmp.begin(), [&](char ch){return toupper(ch);});
			if (driverNameTmp == "NITF")
			{
				isNtif = true;
			}
		}

		// Check for sub data sets...
		char** papszMetadata = GDALGetMetadata( theDataset, "SUBDATASETS" );
		if( CSLCount(papszMetadata) > 0 )
		{
			theSubDatasets.clear();

			for( int i = 0; papszMetadata[i] != 0; ++i )
			{
				std::string os = papszMetadata[i];
				if (os.find("_NAME=") != std::string::npos)
				{
					//Sub sets have already been set. Open each sub-dataset really slow down the process
					//specially for hdf data which sometimes has over 100 sub-datasets. Since following code
					//only for ntif cloud checking, so only open each sub-dataset here if the dataset is
					//nitf. This will be removed eventually when toprs can handle 2GB nitf file. 
					//Otherwise open a sub-dataset when setCurrentEntry() gets called.
					if (isNtif)
					{
						GDALDatasetH subDataset = GDALOpen(filterSubDatasetsString(os).c_str(),
							GA_ReadOnly);
						if ( subDataset != 0 )
						{
							// "Worldview ingest should ignore subimages when NITF_ICAT=CLOUD"
							// Hack: Ignore NITF subimages marked as cloud layers.
							std::string nitfIcatTag( GDALGetMetadataItem( subDataset, "NITF_ICAT", "" ) );
							if ( nitfIcatTag.find("CLOUD") == std::string::npos )
							{
								theSubDatasets.push_back(filterSubDatasetsString(os));
							}
						}
						GDALClose(subDataset);
					}
					else
					{
						theSubDatasets.push_back(filterSubDatasetsString(os));
					}
				}
			}
			//---
			// Have multiple entries.  We're going to default to open the first
			// entry like cidcadrg.
			//---
			close();

			theDataset = GDALOpen(theSubDatasets[theEntryNumberToRender].c_str(),
				GA_ReadOnly);
			if (theDataset == 0)
			{

				return false;
			}
		}  // End of has subsets block.

	}  // End of "if (theSubdatasets.size() == 0)"
	else
	{
		// Sub sets have already been set.
		theDataset = GDALOpen(theSubDatasets[theEntryNumberToRender].c_str(),
			GA_ReadOnly);
		if (theDataset == 0)
		{
			return false;
		}
	}

	// Set the driver.
	theDriver = GDALGetDatasetDriver( theDataset );

	if(!theDriver) return false;


	theGdtType = GDT_Byte;
	theOutputGdtType = GDT_Byte;

	if(getNumberOfInputBands() < 1 )
	{
		if(CSLCount(GDALGetMetadata(theDataset, "SUBDATASETS")))
		{
			std::cout
				<< "torsGdalReader::open WARNING:"
				<< "\nHas multiple sub datasets and need to set the data before"
				<< " we can get to the bands" << std::endl;
		}

		close();
		std::cout
			<< "torsGdalReader::open WARNING:"
			<< "\nNo band data present in torsGdalReader::open" << std::endl;
		return false;
	}

	toprs_int32 i = 0;
	GDALRasterBandH bBand = GDALGetRasterBand( theDataset, 1 );
	theGdtType  = GDALGetRasterDataType(bBand);


	char** papszMetadata = GDALGetMetadata( bBand, NULL );
	if (CSLCount(papszMetadata) > 0)
	{
		for(int i = 0; papszMetadata[i] != NULL; i++ )
		{
			std::string metaStr = papszMetadata[i];

			if (metaStr.find("AREA_OR_POINT") != std::string::npos)
			{
				//std::string pixel_is_point_or_area = metaStr.split("=")[1];
				//pixel_is_point_or_area.downcase();
				//if (pixel_is_point_or_area.contains("area"))
				//	thePixelType = TOPRS_PIXEL_IS_AREA;
				break;
			}
		}
	}

	if(!isIndexed(1))
	{
		for(i = 0; i  < GDALGetRasterCount(theDataset); ++i)
		{
			if(theGdtType != GDALGetRasterDataType(GDALGetRasterBand( theDataset,i+1 )))
			{
				std::cout
					<< "torsGdalReader::open WARNING"
					<< "\nWe currently do not support different scalar type bands."
					<< std::endl;
				close();
				return false;
			}

		}
	}
	theOutputGdtType = theGdtType;
	switch(theGdtType)
	{
	case GDT_CInt16:
		{
			//          theOutputGdtType = GDT_Int16;
			theIsComplexFlag = true;
			break;
		}
	case GDT_CInt32:
		{
			//          theOutputGdtType = GDT_Int32;
			theIsComplexFlag = true;
			break;
		}
	case GDT_CFloat32:
		{
			//          theOutputGdtType = GDT_Float32;
			theIsComplexFlag = true;
			break;
		}
	case GDT_CFloat64:
		{
			//          theOutputGdtType = GDT_Float64;
			theIsComplexFlag = true;
			break;
		}
	default:
		{
			theIsComplexFlag = false;
			break;
		}
	}

	if((std::string(GDALGetDriverShortName( theDriver )) == "PNG")&&
		(getNumberOfInputBands() == 4))
	{
		theAlphaChannelFlag = true;
	}
	populateLut();
	computeMinMax();
	completeOpen();

	theTile = toprsImgFactory::instance()->create(this);
	theSingleBandTile = toprsImgFactory::instance()->create(getInputScalarType(), 1);

	if ( m_preservePaletteIndexesFlag )
	{
		theTile->setIndexedFlag(true);
		theSingleBandTile->setIndexedFlag(true);
	}

	theTile->initialize();
	theSingleBandTile->initialize();
	theGdalBuffer.resize(0);
	if(theIsComplexFlag)
	{
		theGdalBuffer.resize(theSingleBandTile->getSizePerBandInBytes()*2);
	}

	theImageBound = toprsIRect(0
		,0
		,GDALGetRasterXSize(theDataset)-1
		,GDALGetRasterYSize(theDataset)-1);
	int xSize=0, ySize=0;
	GDALGetBlockSize(GDALGetRasterBand( theDataset, 1 ),
		&xSize,
		&ySize);
 
	if (driverNameTmp.find("JPIP")!= std::string::npos || driverNameTmp.find("JP2")!= std::string::npos)
	{
		m_isBlocked = ((xSize > 1)&&(ySize > 1));
	}
	else
	{
		m_isBlocked = false;
	}
	//if(m_isBlocked)
	//{
	//	setRlevelCache();
	//}
	return true;
}
示例#7
0
std::shared_ptr<toprsImg> toprsGadlReader::getTile( const toprsIRect& tileRect, int resLevel/*=0*/ )
{
	// This tile source bypassed, or invalid res level, return a blank tile.
	if (!theDataset)
	{
		return std::shared_ptr<toprsImg>();
	}

	// Check for intersect.
	toprsIRect imageBound = getBoundingRect(resLevel);
	if(!tileRect.intersects(imageBound))
	{
		theTile->setImgRect(tileRect);
		theTile->makeBlank();
		return theTile;
	}

	if(m_isBlocked)
	{
		return getTileBlockRead(tileRect, resLevel);
	}
	// Check for overview.
	if(resLevel)
	{
		if ( m_preservePaletteIndexesFlag )
		{
			// No mechanism for this coded for reduce resolution levels.
			std::cout << std::string("toprsGdalReader::getTile ERROR: Accessing reduced resolution level with the preservePaletteIndexesFlag set!") ;
			return std::shared_ptr<toprsImg>();//xizhi
		}

		//if(theOverview.valid() && theOverview->isValidRLevel(resLevel))//xizhi
		//{
		//	std::shared_ptr<toprsImg> tileData = theOverview->getTile(tileRect, resLevel);
		//	tileData->setDataType(getOutputScalarType());
		//	return tileData;
		//}

#if 1
		//---
		// Note: This code was shut off since we currently don't utilize gdal overviews.
		// toprsGdalReader::getNumberOfDecimationLevels has been fixed accordingly.
		
		//---
		//else if(GDALGetRasterCount(theDataset))
		//{
		//	GDALRasterBandH band = GDALGetRasterBand(theDataset, 1);
		//	if(static_cast<int>(resLevel) > GDALGetOverviewCount(band))
		//	{
		//		return std::shared_ptr<toprsImg>();
		//	}
		//}
#endif
	}

	// Set the rectangle of the tile.
	theTile->setImgRect(tileRect);

	// Compute clip rectangle with respect to the image bounds.
	toprsIRect clipRect   = tileRect.clipToRect(imageBound);

	theSingleBandTile->setImgRect(clipRect);

	if (tileRect.completely_within(clipRect) == false)
	{
		// Not filling whole tile so blank it out first.
		theTile->makeBlank();
	}

	// Always blank the single band tile.
	theSingleBandTile->makeBlank();

	toprs_uint32 anToprsBandIndex = 0;
	toprs_uint32 aGdalBandIndex   = 1;

	toprs_uint32 rasterCount = GDALGetRasterCount(theDataset);
	if (m_outputBandList.size() > 0)
	{
		rasterCount = (toprs_uint32) m_outputBandList.size();
	}

	toprs_uint32 outputBandIndex = 0;
	for(toprs_uint32 aBandIndex =1; aBandIndex <= rasterCount; ++aBandIndex)
	{
		if (m_outputBandList.size() > 0)
		{
			aGdalBandIndex = m_outputBandList[outputBandIndex] + 1;
			outputBandIndex++;
		}
		else
		{
			aGdalBandIndex = aBandIndex;
		}
		GDALRasterBandH aBand = resolveRasterBand( resLevel, aGdalBandIndex );
		if ( aBand )
		{
			bool bReadSuccess;
			if(!theIsComplexFlag)
			{
				bReadSuccess = (GDALRasterIO(aBand
					, GF_Read
					, clipRect.left_up().x
					, clipRect.left_up().y
					, clipRect.width()
					, clipRect.height()
					, theSingleBandTile->getBuf()
					, clipRect.width()
					, clipRect.height()
					, theOutputGdtType
					, 0 
					, 0 ) == CE_None) ? true : false;

				if ( bReadSuccess == true )
				{
					if(isIndexed(aGdalBandIndex))
					{
						if(isIndexTo3Band(aGdalBandIndex))
						{
							if ( m_preservePaletteIndexesFlag )
							{
								theTile->loadBand((void*)theSingleBandTile->getBuf(),
									clipRect, anToprsBandIndex);
								anToprsBandIndex += 1;
							}
							else
							{
								loadIndexTo3BandTile(clipRect, aGdalBandIndex, anToprsBandIndex);
								anToprsBandIndex+=3;
							}
						}
						else if(isIndexTo1Band(aGdalBandIndex))
						{ 
							// ??? Ignoring (drb)
							anToprsBandIndex += 1;
						}
					}
					else
					{
						if(theAlphaChannelFlag&&(aGdalBandIndex==rasterCount))
						{
							theTile->nullTileAlpha((toprs_uint8*)theSingleBandTile->getBuf(),
								theSingleBandTile->getImgRect(),
								clipRect,
								false);
						}
						else
						{
							// Note fix rectangle to represent theBuffer's rect in image space.
							theTile->loadBand((void*)theSingleBandTile->getBuf()
								, clipRect
								, anToprsBandIndex);
							++anToprsBandIndex;
						}
					}
				}
				else
				{
					++anToprsBandIndex;
				}
			} 
			else // matches if(!theIsComplexFlag){} 
			{
				bReadSuccess = (GDALRasterIO(aBand
					, GF_Read
					, clipRect.left_up().x
					, clipRect.left_up().y
					, clipRect.width()
					, clipRect.height()
					, &theGdalBuffer.front()
					, clipRect.width()
					, clipRect.height()
					, theOutputGdtType
					, 0
					, 0 ) == CE_None) ? true : false;
				if (  bReadSuccess == true )
				{
					toprs_uint32 byteSize = toprs::dataSizeInBytes(theSingleBandTile->getDataType());
					toprs_uint32 byteSize2 = byteSize*2;
					toprs_uint8* complexBufPtr = (toprs_uint8*)(&theGdalBuffer.front()); // start at first real part
					toprs_uint8* outBufPtr  = (toprs_uint8*)(theSingleBandTile->getBuf());
					toprs_uint32 idxMax = theSingleBandTile->w()*theSingleBandTile->h();
					toprs_uint32 idx = 0;
					for(idx = 0; idx < idxMax; ++idx)
					{
						memcpy(outBufPtr, complexBufPtr, byteSize);
						complexBufPtr += byteSize2;
						outBufPtr     += byteSize;
					}
					theTile->loadBand((void*)theSingleBandTile->getBuf()
						, clipRect
						, anToprsBandIndex);
					++anToprsBandIndex;
					complexBufPtr = (toprs_uint8*)(&theGdalBuffer.front()) + byteSize; // start at first imaginary part
					outBufPtr  = (toprs_uint8*)(theSingleBandTile->getBuf());
					for(idx = 0; idx < idxMax; ++idx)
					{
						memcpy(outBufPtr, complexBufPtr, byteSize);
						complexBufPtr += byteSize2;
						outBufPtr     += byteSize;
					}
					theTile->loadBand((void*)theSingleBandTile->getBuf()
						, clipRect
						, anToprsBandIndex);
					++anToprsBandIndex;
				}
				else
				{
					anToprsBandIndex += 2;
				}
			}
		}
	}

	theTile->validate();
	return theTile;
}
示例#8
0
文件: gvmanager.c 项目: Onjrew/OpenEV
GvRaster *gv_manager_get_dataset_raster( GvManager *manager, 
                                         GDALDatasetH dataset, int band )

{
    int       i;
    GvDataset *ds = NULL;
    GvSampleMethod sm;
    const char *sm_pref;

    if( band < 1 || band > GDALGetRasterCount(dataset) )
        return NULL;

    /* 
     * Find in our list.  The dataset must already be "under management".
     */
    for( i = 0; i < manager->datasets->len; i++ )
    {
        ds = (GvDataset *) g_ptr_array_index(manager->datasets, i);

        if( dataset == ds->dataset )
            break;
    }

    if( i == manager->datasets->len )
    {
        g_warning( "gv_manager_get_dataset_raster called with unmanaged dataset" );
        return NULL;
    }

    /*
     * Figure out the sample method to use from the preferences.
     */
    sm_pref = gv_manager_get_preference( manager, "default_raster_sample");
    if( sm_pref != NULL && EQUAL(sm_pref,"average") )
        sm = GvSMAverage;
    else if( sm_pref != NULL && EQUAL(sm_pref,"average_8bit_phase") )
        sm = GvSMAverage8bitPhase;
    else
        sm = GvSMSample;

    /* 
     * Create a new GvRaster if it doesn't already exist.
     */

    if( ds->rasters[band-1] == NULL )
    {
        GDALRasterBandH gdal_band;

        gdal_band = GDALGetRasterBand( ds->dataset, band );
        if( GDALGetRasterColorInterpretation(gdal_band) == GCI_PaletteIndex )
            sm = GvSMSample;

        ds->rasters[band-1] = GV_RASTER(gv_raster_new( ds->dataset, band, sm));
        gtk_signal_connect(
            GTK_OBJECT(ds->rasters[band-1]), "destroy", 
            GTK_SIGNAL_FUNC(gv_manager_raster_destroy_cb),
            GTK_OBJECT(manager));
    }

    return ds->rasters[band-1];
}
bool QgsImageWarper::createDestinationDataset(
  const QString &outputName, GDALDatasetH hSrcDS, GDALDatasetH &hDstDS,
  uint resX, uint resY, double *adfGeoTransform, bool useZeroAsTrans,
  const QString& compression, const QString &projection )
{
  // create the output file
  GDALDriverH driver = GDALGetDriverByName( "GTiff" );
  if ( !driver )
  {
    return false;
  }
  char **papszOptions = NULL;
  papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", compression.toAscii() );
  hDstDS = GDALCreate( driver,
                       QFile::encodeName( outputName ).constData(), resX, resY,
                       GDALGetRasterCount( hSrcDS ),
                       GDALGetRasterDataType( GDALGetRasterBand( hSrcDS, 1 ) ),
                       papszOptions );
  if ( !hDstDS )
  {
    return false;
  }

  if ( CE_None != GDALSetGeoTransform( hDstDS, adfGeoTransform ) )
  {
    return false;
  }

  if ( !projection.isEmpty() )
  {
    OGRSpatialReference oTargetSRS;
    if ( projection.startsWith( "EPSG", Qt::CaseInsensitive ) )
    {
      QString epsg = projection.mid( projection.indexOf( ":" ) + 1 );
      oTargetSRS.importFromEPSG( epsg.toInt() );
    }
    else
    {
      oTargetSRS.importFromProj4( projection.toLatin1().data() );
    }

    char *wkt = NULL;
    OGRErr err = oTargetSRS.exportToWkt( &wkt );
    if ( err != CE_None || GDALSetProjection( hDstDS, wkt ) != CE_None )
    {
      OGRFree( wkt );
      return false;
    }
    OGRFree( wkt );
  }

  for ( int i = 0; i < GDALGetRasterCount( hSrcDS ); ++i )
  {
    GDALRasterBandH hSrcBand = GDALGetRasterBand( hSrcDS, i + 1 );
    GDALRasterBandH hDstBand = GDALGetRasterBand( hDstDS, i + 1 );
    GDALColorTableH cTable = GDALGetRasterColorTable( hSrcBand );
    GDALSetRasterColorInterpretation( hDstBand, GDALGetRasterColorInterpretation( hSrcBand ) );
    if ( cTable )
    {
      GDALSetRasterColorTable( hDstBand, cTable );
    }

    int success;
    double noData = GDALGetRasterNoDataValue( hSrcBand, &success );
    if ( success )
    {
      GDALSetRasterNoDataValue( hDstBand, noData );
    }
    else if ( useZeroAsTrans )
    {
      GDALSetRasterNoDataValue( hDstBand, 0 );
    }
  }

  return true;
}
int main( int argc, const char* argv[] )
{
    GDALDriverH   hDriver;
    double        adfGeoTransform[6];
    GDALDatasetH  in_Dataset;
    GDALDatasetH  mask_Dataset;
    GDALDatasetH  out_Dataset;
    GDALRasterBandH mask_band;
    char            *mask_scan_line, *data_scan_line;
    int             nBlockXSize, nBlockYSize;
    int             bGotMin, bGotMax;
    int             bands;
    int             xsize;
    double          adfMinMax[2];
    
    GDALAllRegister();
    
    if ( argc != 2) {
        printf("Usage: %s <file to add mask to> \n", argv[0]);
        printf("This utility adds a nodata mask to a file, were the datadata value is \"0\"\n");
        printf("contact/blame [email protected] for questions/problems.\n");
        return 0;
    }
    
    /* open datasets..*/
    in_Dataset = GDAL_open( argv[1]);
    
    /* add mask.. */
    GDALCreateDatasetMaskBand( in_Dataset, 0);
    
    /* Basic info on source dataset..*/
    GDALGetBlockSize(GDALGetRasterBand( in_Dataset, 1 ) , &nBlockXSize, &nBlockYSize );
    printf( "Block=%dx%d Type=%s, ColorInterp=%s\n",
                nBlockXSize, nBlockYSize,
                GDALGetDataTypeName(GDALGetRasterDataType( GDALGetRasterBand( in_Dataset, 1 ))),
                GDALGetColorInterpretationName(
                    GDALGetRasterColorInterpretation(GDALGetRasterBand( in_Dataset, 1 ))));
    
    /* Loop though bands, wiping values with mask values of 0.. */
    xsize = GDALGetRasterXSize( in_Dataset );
    mask_scan_line = (char *) CPLMalloc(sizeof(char)*xsize);
    data_scan_line = (char *) CPLMalloc(sizeof(char)*xsize);
    for (bands=1; bands <= GDALGetRasterCount( in_Dataset ); bands ++ ) {
        int x;
        GDALRasterBandH data_band, out_band;
        int y_index = 0;
        
        printf("INFO: Doing band %d of %d\n", bands,GDALGetRasterCount( in_Dataset ) );
        data_band =  GDALGetRasterBand( in_Dataset, bands);
        mask_band = GDALGetMaskBand(data_band);
        for (y_index = 0; y_index <GDALGetRasterYSize( in_Dataset ); y_index ++ ) {
            /* Read data..*/
            GDALRasterIO( data_band, GF_Read, 0, y_index, xsize , 1, data_scan_line, xsize , 1, GDT_Byte, 0, 0 );
            
            for(x=0; x < xsize; x++) {
                /* if mask is set to 0, then mask off...*/
                /* lame nodata handleing, but such is life.. */
                if ( data_scan_line[x] == 0 )
                    mask_scan_line[x]=0;
                else
                    mask_scan_line[x]=255;
            }
            
            /* now write out band..*/
            GDALRasterIO( mask_band, GF_Write, 0, y_index, xsize , 1, mask_scan_line, xsize , 1, GDT_Byte, 0, 0 );
        }
        
    }
    
    GDALClose(in_Dataset);
}
示例#11
0
static ERL_NIF_TERM gdal_nif_get_meta(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    gdal_img_handle* handle;
    if (enif_get_resource(env, argv[0], gdal_img_RESOURCE, (void**)&handle)) {
        GDALDatasetH in_ds = handle->in_ds;
        if (in_ds != NULL) {
            ERL_NIF_TERM terms[8];
            int idx = 0;

            terms[idx++] = enif_make_tuple2(env,
                                enif_make_atom(env, "description"),
                                enif_make_string(env, GDALGetDescription(in_ds), ERL_NIF_LATIN1));

            GDALDriverH hDriver = GDALGetDatasetDriver(in_ds);
            char buf[256];
            sprintf(buf, "%s/%s", 
                    GDALGetDriverShortName(hDriver), GDALGetDriverLongName(hDriver));
            terms[idx++] = enif_make_tuple2(env, 
                                enif_make_atom(env, "driver"),
                                enif_make_string(env, buf, ERL_NIF_LATIN1));

            terms[idx++] = enif_make_tuple2(env, 
                                enif_make_atom(env, "rasterSize"), 
                                enif_make_tuple2(env, 
                                    enif_make_int(env, GDALGetRasterXSize(in_ds)), 
                                    enif_make_int(env, GDALGetRasterYSize(in_ds))));

            terms[idx++] = enif_make_tuple2(env, 
                                    enif_make_atom(env, "rasterCount"),
                                    enif_make_int(env, GDALGetRasterCount(in_ds)));

            double adfGeoTransform[6];
            if( GDALGetGeoTransform( in_ds, adfGeoTransform ) == CE_None ) {
                terms[idx++] = enif_make_tuple2(env,
                                    enif_make_atom(env, "origin"),
                                    enif_make_tuple2(env,
                                        enif_make_double(env, adfGeoTransform[0]), 
                                        enif_make_double(env, adfGeoTransform[3])));

                terms[idx++] = enif_make_tuple2(env,
                                    enif_make_atom(env, "pixelSize"), 
                                    enif_make_tuple2(env, 
                                        enif_make_double(env, adfGeoTransform[1]), 
                                        enif_make_double(env, adfGeoTransform[5])));
            }

            if (GDALGetProjectionRef(in_ds) != NULL) {
                terms[idx++] = enif_make_tuple2(env,
                                    enif_make_atom(env, "projection"), 
                                    enif_make_string(env, 
                                        GDALGetProjectionRef(in_ds), ERL_NIF_LATIN1));
}

            char** fileList = GDALGetFileList(in_ds);
            if (fileList != NULL) {
                ERL_NIF_TERM fileTerms[16];
                int fileIdx = 0;
                char** files = fileList;

                do {
                    fileTerms[ fileIdx++ ] = enif_make_string(env, *files, ERL_NIF_LATIN1);
                } while(*(++files)) ;
                CSLDestroy(fileList);

                terms[idx++] = enif_make_tuple2(env,
                                    enif_make_atom(env, "fileList"),
                                    enif_make_list_from_array(env, fileTerms, fileIdx));
            }

            return enif_make_list_from_array(env, terms, idx);
        }
        else {
            return ATOM_NOT_OPEN;
        }
    }
    else {
        return enif_make_badarg(env);
    }
}
示例#12
0
// build out_ds
static ERL_NIF_TERM gdal_nif_create_warped_vrtimg(ErlNifEnv* env, int argc,
                                          const ERL_NIF_TERM argv[])
{
    ErlNifBinary filenameBin;
    if (!enif_inspect_iolist_as_binary(env, argv[0], &filenameBin) || 
        (filenameBin.size >= FILENAME_LEN)) {
        return make_error_msg(env, "filename error, maybe too long");
    }

    char imgfilename[FILENAME_LEN] = "";
    size_t name_sz = filenameBin.size;
    memcpy(imgfilename, filenameBin.data, filenameBin.size);
    DEBUG("img filename: %s\r\n", imgfilename);

    int epsg_code;
    if (!enif_get_int(env, argv[1], &epsg_code)) {
        return enif_make_badarg(env);
    }

    GDALDatasetH in_ds = GDALOpenShared(imgfilename, GA_ReadOnly);
    if (in_ds == NULL) {
        const char* msg = "It is not possible to open the input file '%s'.";
        char errstr[name_sz + strlen(msg) + 1];
        sprintf(errstr, msg, imgfilename);
        return make_error_msg(env, errstr);
    }

    gdal_img_handle* handle = enif_alloc_resource(
                                            gdal_img_RESOURCE, 
                                            sizeof(gdal_img_handle));
    memset(handle, '\0', sizeof(*handle));
    handle->in_ds = in_ds;
    handle->options_resampling = "average";
    handle->querysize = 256 * 4;
    handle->tilesize = 256;

    int rasterCount = GDALGetRasterCount(in_ds);
    if (rasterCount == 0) {
        const char* msg = "Input file '%s' has no raster band";
        char errstr[name_sz + strlen(msg) + 1];
        sprintf(errstr, msg, imgfilename);

        destroy_img_handle(handle);
        return make_error_msg(env, errstr);
    }

    GDALRasterBandH hBand = GDALGetRasterBand(in_ds, 1);
    if (GDALGetRasterColorTable(hBand) != NULL) {
        const char* msg = 
            "Please convert this file to RGB/RGBA and run gdal2tiles on the result.\n" 
            "From paletted file you can create RGBA file (temp.vrt) by:\n"
            "gdal_translate -of vrt -expand rgba %s temp.vrt\n"
            "then run this program: gdal2tiles temp.vrt";
        char errstr[name_sz + strlen(msg) + 1];
        sprintf(errstr, msg, imgfilename);

        destroy_img_handle(handle);
        return make_error_msg(env, errstr);
    }

    double padfTransform[6];
    double errTransform[6] = {0.0, 1.0, 0.0, 0.0, 0.0, 1.0};
    GDALGetGeoTransform(in_ds, padfTransform);
    if (0 == memcmp(padfTransform, errTransform, sizeof(errTransform))
             && GDALGetGCPCount(in_ds) == 0) {
        destroy_img_handle(handle);
        return make_error_msg(env, 
                              "There is no georeference - "
                              "neither affine transformation (worldfile) nor GCPs");
    }

    const char* in_srs_wkt = GDALGetProjectionRef(in_ds);
    if (in_srs_wkt == NULL && GDALGetGCPCount(in_ds) != 0) {
        in_srs_wkt = GDALGetGCPProjection(in_ds);
    }
    char* out_srs_wkt = get_wkt_of(epsg_code);
    GDALDatasetH out_ds = GDALAutoCreateWarpedVRT(in_ds, 
                                                  in_srs_wkt, 
                                                  out_srs_wkt, 
                                                  GRA_NearestNeighbour, 
                                                  0.0, 
                                                  NULL);
    handle->out_ds = out_ds;
    OGRFree(out_srs_wkt);


    handle->alphaBand = GDALGetMaskBand(GDALGetRasterBand(handle->out_ds, 1));
    rasterCount = GDALGetRasterCount(handle->out_ds);
    unsigned int dataBandsCount;
    if (GDALGetMaskFlags(handle->alphaBand) & GMF_ALPHA || 
            rasterCount == 4 || rasterCount == 2) {
        dataBandsCount = rasterCount - 1;
    }
    else {
        dataBandsCount = rasterCount;
    }
    handle->dataBandsCount = dataBandsCount;
    handle->tilebands = dataBandsCount + 1;


    ERL_NIF_TERM imginfo = get_imginfo(env, out_ds);
    if (enif_compare(ATOM_ERROR, imginfo) == 0) {
        destroy_img_handle(handle);
        return make_error_msg(env,
                              "Georeference of the raster contains rotation or skew. "
                              "Such raster is not supported. "
                              "Please use gdalwarp first");
    }

    ERL_NIF_TERM imgref = enif_make_resource(env, handle);
    enif_release_resource(handle);

    return enif_make_tuple3(env, ATOM_OK, imgref, imginfo);
}
int
main (int argc, const char *argv[])
{
  GDALDriverH hDriver;
  double adfGeoTransform[6];
  GDALDatasetH in_Dataset;
  GDALDatasetH mask_Dataset;
  GDALDatasetH out_Dataset;
  GDALRasterBandH mask_band;
  unsigned char *out_scan_line, *data_scan_line;
  int nBlockXSize, nBlockYSize;
  int bGotMin, bGotMax;
  int bands;
  int xsize;
  double adfMinMax[2];
  int valid_data_pixels[10];
  int saturated_data_pixels[10];
  int y_index, x;
  GDALRasterBandH out_band;


  if (argc != 3)
    {
      ussage (argv[0]);
    }


  GDALAllRegister ();

  /* Set cache to something reasonable.. - 1/2 gig */
  CPLSetConfigOption ("GDAL_CACHEMAX", "512");

  /* open datasets.. */
  in_Dataset = GDAL_open_read (argv[1]);
  out_Dataset = make_me_a_sandwitch (&in_Dataset, argv[2]);

  /* Basic info on source dataset.. */
  GDALGetBlockSize (GDALGetRasterBand (in_Dataset, 1), &nBlockXSize,
		    &nBlockYSize);

  /* Loop though bands, checking for saturated pixels .... */
  xsize = GDALGetRasterXSize (in_Dataset);
  data_scan_line = (char *) CPLMalloc (sizeof (char) * xsize);
  out_scan_line = (char *) CPLMalloc (sizeof (char) * xsize);

  /* The output band... */
  out_band = GDALGetRasterBand (out_Dataset, 1);


  /* wipe counters.. */
  for (bands = 1; bands <= GDALGetRasterCount (in_Dataset); bands++)
    {
      valid_data_pixels[bands] = 0;
      saturated_data_pixels[bands] = 0;
    }

  /* loop though the lines of the data, looking for no data and saturated pixels.. */
  for (y_index = 0; y_index < GDALGetRasterYSize (in_Dataset); y_index++)
    {
      for (bands = 1; bands <= GDALGetRasterCount (in_Dataset); bands++)
	{
	  GDALRasterBandH data_band;
	  /* Read data.. */
	  data_band = GDALGetRasterBand (in_Dataset, bands);
	  GDALRasterIO (data_band, GF_Read, 0, y_index, xsize, 1,
			data_scan_line, xsize, 1, GDT_Byte, 0, 0);
	  /* If first band, then copy into output slice.. */
	  if (bands == 1)
	    {
	      unsigned char data_value;
	      for (x = 0; x < xsize; x++)
		{
		  /*shift to make darker... */
		  out_scan_line[x] = data_scan_line[x] >> 1;
		  if (out_scan_line[x] == 0 && data_scan_line[x] != 0)
		    {
		      out_scan_line[x] = 1;
		    }
		}
	    }

	  /* Loop though, looking for saturated pixels and no-data values.. */
	  for (x = 0; x < xsize; x++)
	    {
	      if (data_scan_line[x] == 0)
		{
		  out_scan_line[x] = 255;
		}
	    }
	}
      GDALRasterIO (out_band, GF_Write, 0, y_index, xsize, 1, out_scan_line,
		    xsize, 1, GDT_Byte, 0, 0);
    }
示例#14
0
int main( int argc, char ** argv )

{
    GDALDatasetH	hSrcDS, hDstDS;
    const char         *pszFormat = "GTiff";
    char               *pszTargetSRS = NULL;
    char               *pszSourceSRS = NULL;
    const char         *pszSrcFilename = NULL, *pszDstFilename = NULL;
    int                 bCreateOutput = FALSE, i, nOrder = 0;
    void               *hTransformArg, *hGenImgProjArg=NULL, *hApproxArg=NULL;
    char               **papszWarpOptions = NULL;
    double             dfErrorThreshold = 0.125;
    GDALTransformerFunc pfnTransformer = NULL;
    char                **papszCreateOptions = NULL;

    GDALAllRegister();

/* -------------------------------------------------------------------- */
/*      Parse arguments.                                                */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i],"--version") )
        {
            printf( "%s\n", GDALVersionInfo( "--version" ) );
            exit( 0 );
        }
        else if( EQUAL(argv[i],"--formats") )
        {
            int iDr;

            printf( "Supported Formats:\n" );
            for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ )
            {
                GDALDriverH hDriver = GDALGetDriver(iDr);
                
                printf( "  %s: %s\n",
                        GDALGetDriverShortName( hDriver ),
                        GDALGetDriverLongName( hDriver ) );
            }

            exit( 0 );
        }
        else if( EQUAL(argv[i],"-co") && i < argc-1 )
        {
            papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] );
            bCreateOutput = TRUE;
        }   
        else if( EQUAL(argv[i],"-of") && i < argc-1 )
        {
            pszFormat = argv[++i];
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-t_srs") && i < argc-1 )
        {
            pszTargetSRS = SanitizeSRS(argv[++i]);
        }
        else if( EQUAL(argv[i],"-s_srs") && i < argc-1 )
        {
            pszSourceSRS = SanitizeSRS(argv[++i]);
        }
        else if( EQUAL(argv[i],"-order") && i < argc-1 )
        {
            nOrder = atoi(argv[++i]);
        }
        else if( EQUAL(argv[i],"-et") && i < argc-1 )
        {
            dfErrorThreshold = CPLAtof(argv[++i]);
        }
        else if( EQUAL(argv[i],"-tr") && i < argc-2 )
        {
            dfXRes = CPLAtof(argv[++i]);
            dfYRes = fabs(CPLAtof(argv[++i]));
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-ts") && i < argc-2 )
        {
            nForcePixels = atoi(argv[++i]);
            nForceLines = atoi(argv[++i]);
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-te") && i < argc-4 )
        {
            dfMinX = CPLAtof(argv[++i]);
            dfMinY = CPLAtof(argv[++i]);
            dfMaxX = CPLAtof(argv[++i]);
            dfMaxY = CPLAtof(argv[++i]);
            bCreateOutput = TRUE;
        }
        else if( argv[i][0] == '-' )
            Usage();
        else if( pszSrcFilename == NULL )
            pszSrcFilename = argv[i];
        else if( pszDstFilename == NULL )
            pszDstFilename = argv[i];
        else
            Usage();
    }

    if( pszDstFilename == NULL )
        Usage();

/* -------------------------------------------------------------------- */
/*      Open source dataset.                                            */
/* -------------------------------------------------------------------- */
    hSrcDS = GDALOpen( pszSrcFilename, GA_ReadOnly );
    
    if( hSrcDS == NULL )
        exit( 2 );

/* -------------------------------------------------------------------- */
/*      Check that there's at least one raster band                     */
/* -------------------------------------------------------------------- */
    if ( GDALGetRasterCount(hSrcDS) == 0 )
    {
        fprintf(stderr, "Input file %s has no raster bands.\n", pszSrcFilename );
        exit( 2 );
    }

    if( pszSourceSRS == NULL )
    {
        if( GDALGetProjectionRef( hSrcDS ) != NULL 
            && strlen(GDALGetProjectionRef( hSrcDS )) > 0 )
            pszSourceSRS = CPLStrdup(GDALGetProjectionRef( hSrcDS ));

        else if( GDALGetGCPProjection( hSrcDS ) != NULL
                 && strlen(GDALGetGCPProjection(hSrcDS)) > 0 
                 && GDALGetGCPCount( hSrcDS ) > 1 )
            pszSourceSRS = CPLStrdup(GDALGetGCPProjection( hSrcDS ));
        else
            pszSourceSRS = CPLStrdup("");
    }

    if( pszTargetSRS == NULL )
        pszTargetSRS = CPLStrdup(pszSourceSRS);

/* -------------------------------------------------------------------- */
/*      Does the output dataset already exist?                          */
/* -------------------------------------------------------------------- */
    CPLPushErrorHandler( CPLQuietErrorHandler );
    hDstDS = GDALOpen( pszDstFilename, GA_Update );
    CPLPopErrorHandler();

    if( hDstDS != NULL && bCreateOutput )
    {
        fprintf( stderr, 
                 "Output dataset %s exists,\n"
                 "but some commandline options were provided indicating a new dataset\n"
                 "should be created.  Please delete existing dataset and run again.",
                 pszDstFilename );
        exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      If not, we need to create it.                                   */
/* -------------------------------------------------------------------- */
    if( hDstDS == NULL )
    {
        hDstDS = GDALWarpCreateOutput( hSrcDS, pszDstFilename, pszFormat, 
                                       pszSourceSRS, pszTargetSRS, nOrder,
                                       papszCreateOptions );
        papszWarpOptions = CSLSetNameValue( papszWarpOptions, "INIT", "0" );
        CSLDestroy( papszCreateOptions );
        papszCreateOptions = NULL;
    }

    if( hDstDS == NULL )
        exit( 1 );

/* -------------------------------------------------------------------- */
/*      Create a transformation object from the source to               */
/*      destination coordinate system.                                  */
/* -------------------------------------------------------------------- */
    hTransformArg = hGenImgProjArg = 
        GDALCreateGenImgProjTransformer( hSrcDS, pszSourceSRS, 
                                         hDstDS, pszTargetSRS, 
                                         TRUE, 1000.0, nOrder );

    if( hTransformArg == NULL )
        exit( 1 );

    pfnTransformer = GDALGenImgProjTransform;

/* -------------------------------------------------------------------- */
/*      Warp the transformer with a linear approximator unless the      */
/*      acceptable error is zero.                                       */
/* -------------------------------------------------------------------- */
    if( dfErrorThreshold != 0.0 )
    {
        hTransformArg = hApproxArg = 
            GDALCreateApproxTransformer( GDALGenImgProjTransform, 
                                         hGenImgProjArg, dfErrorThreshold );
        pfnTransformer = GDALApproxTransform;
    }

/* -------------------------------------------------------------------- */
/*      Now actually invoke the warper to do the work.                  */
/* -------------------------------------------------------------------- */
    GDALSimpleImageWarp( hSrcDS, hDstDS, 0, NULL, 
                         pfnTransformer, hTransformArg,
                         GDALTermProgress, NULL, papszWarpOptions );

    CSLDestroy( papszWarpOptions );

    if( hApproxArg != NULL )
        GDALDestroyApproxTransformer( hApproxArg );

    if( hGenImgProjArg != NULL )
        GDALDestroyGenImgProjTransformer( hGenImgProjArg );

/* -------------------------------------------------------------------- */
/*      Cleanup.                                                        */
/* -------------------------------------------------------------------- */
    GDALClose( hDstDS );
    GDALClose( hSrcDS );

    GDALDumpOpenDatasets( stderr );

    GDALDestroyDriverManager();
    
    exit( 0 );
}
示例#15
0
void toprsGadlReader::computeMinMax()
{
	toprs_uint32 bands = GDALGetRasterCount(theDataset);

	if(theMinPixValues)
	{
		delete [] theMinPixValues;
		theMinPixValues = 0;
	}
	if(theMaxPixValues)
	{
		delete [] theMaxPixValues;
		theMaxPixValues = 0;
	}
	if(theNullPixValues)
	{
		delete [] theNullPixValues;
		theNullPixValues = 0;
	}
	if(isIndexTo3Band())
	{
		int i = 0;
		theMinPixValues  = new double[3];
		theMaxPixValues  = new double[3];
		theNullPixValues = new double[3];

		for(i = 0; i < 3; ++i)
		{
			theMinPixValues[i] = 1;
			theMaxPixValues[i] = 255;
			theNullPixValues[i] = 0;
		}
	}
	else if(isIndexTo1Band())
	{
		theMinPixValues  = new double[1];
		theMaxPixValues  = new double[1];
		theNullPixValues = new double[1];

		*theNullPixValues = 0;
		*theMaxPixValues = 255;
		*theMinPixValues = 1;
	}
	else
	{
		if(!theMinPixValues && !theMaxPixValues&&bands)
		{
			theMinPixValues = new double[bands];
			theMaxPixValues = new double[bands];
			theNullPixValues = new double[bands];
		}
		for(toprs_int32 band = 0; band < (toprs_int32)bands; ++band)
		{
			GDALRasterBandH aBand=0;

			aBand = GDALGetRasterBand(theDataset, band+1);

			int minOk=1;
			int maxOk=1;
			int nullOk=1;

			if(aBand)
			{
				if(hasData())
				{
					theMinPixValues[band] = theData.getMinPix(band);
					theMaxPixValues[band] = theData.getMaxPix(band);
					theNullPixValues[band] = theData.getNullPix(band);
				}
				else 
				{
					std::string driverName = theDriver ? GDALGetDriverShortName( theDriver ) : "";

					// Allow to rescale the image data 
					// to the min/max values found in the raster data only 
					// if it was not acquired with the following drivers:
					if ( driverName.find("JP2KAK") != std::string::npos  ||
						driverName.find("JPEG2000") != std::string::npos||
						driverName.find("NITF") != std::string::npos)
					{
						theMinPixValues[band] = toprs::defaultMin(getOutputScalarType());
						theMaxPixValues[band] = toprs::defaultMax(getOutputScalarType());
						theNullPixValues[band] = toprs::defaultNull(getOutputScalarType());
					}
					else
					{
						theMinPixValues[band]  = GDALGetRasterMinimum(aBand, &minOk);
						theMaxPixValues[band]  = GDALGetRasterMaximum(aBand, &maxOk);
						theNullPixValues[band] = GDALGetRasterNoDataValue(aBand, &nullOk);
					}
					if((!nullOk)||(theNullPixValues[band] < toprs::defaultNull(getOutputScalarType())))
					{
						theNullPixValues[band] = toprs::defaultNull(getOutputScalarType());
					}
				}
				if(!minOk||!maxOk)
				{
					theMinPixValues[band] = toprs::defaultMin(getOutputScalarType());
					theMaxPixValues[band] = toprs::defaultMax(getOutputScalarType());
				}
			}
			else
			{
				theMinPixValues[band] = toprs::defaultMin(getOutputScalarType());
				theMaxPixValues[band] = toprs::defaultMax(getOutputScalarType());
			}
		}
	}
}
示例#16
0
int main(void)
{
	GDALAllRegister();
	/*Open a file*/
	GDALDatasetH hDataset;
	hDataset = GDALOpen( "./dem.tif", GA_ReadOnly );
	if( hDataset == NULL ) printf("The dataset is NULL!\n");
	/*Getting Dasetset Information*/
	GDALDriverH hDriver;
	double adfGeoTransform[6];
	hDriver = GDALGetDatasetDriver( hDataset );
	printf( "Driver: %s/%s\n",
			GDALGetDriverShortName( hDriver ),
			GDALGetDriverLongName( hDriver ));
	printf("Size is %dx%dx%d\n",
			GDALGetRasterXSize( hDataset ),
			GDALGetRasterYSize( hDataset ),
			GDALGetRasterCount( hDataset ));
	if( GDALGetProjectionRef( hDataset ) != NULL )
		printf("Projection is '%s'\n", GDALGetProjectionRef( hDataset ) );
	if (GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None )
	{
		printf("Origin = (%.6f,%.6f)\n",
				adfGeoTransform[0], adfGeoTransform[3]);
		printf( "Pixel Size = (%.6f,%.6f)\n",
				adfGeoTransform[0], adfGeoTransform[5]);
	}
	/*Fetching a Raster Band*/
	GDALRasterBandH hBand;
	int nBlockXSize, nBlockYSize;
	int bGotMin, bGotMax;
	double adfMinMax[2];
	hBand = GDALGetRasterBand( hDataset, 1);
	GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize);
	printf( "Block=%dx%d Type=%s, ColorInterp=%s\n",
			nBlockXSize, nBlockYSize,
			GDALGetDataTypeName(GDALGetRasterDataType(hBand)),
			GDALGetColorInterpretationName(
				GDALGetRasterColorInterpretation(hBand)) );
	adfMinMax[0] = GDALGetRasterMinimum( hBand, &bGotMin );
	adfMinMax[1] = GDALGetRasterMaximum( hBand, &bGotMax );
	if( !(bGotMin && bGotMax) )
	{
		GDALComputeRasterMinMax( hBand, TRUE, adfMinMax );
	}
	printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1]);
	if(GDALGetOverviewCount(hBand) > 0)
		printf( "Band has %d overviews.\n", GDALGetOverviewCount(hBand));
	if( GDALGetRasterColorTable( hBand ) != NULL)
		printf( "Band has a color table with %d entries.\n",
				GDALGetColorEntryCount(
					GDALGetRasterColorTable( hBand)));
	/*Reading Raster Data*/
	float *pafScanline;
	int nXSize = GDALGetRasterBandXSize( hBand );
	pafScanline = (float *)CPLMalloc(sizeof(float)*nXSize);
	GDALRasterIO(hBand, GF_Read, 0, 0, nXSize, 1,
			pafScanline, nXSize, 1, GDT_Float32, 0, 0);
	CPLFree(pafScanline);
	return 0;
}
示例#17
0
int main(int argc, char* argv[])
{
	fprintf(stderr, "TASSELED CAP TRANSFORMATION\nVersion %s.%s. Free software. GNU General Public License, version 3\n", PROG_VERSION, DATE_VERSION);
	fprintf(stderr, "Copyright (C) 2016 Igor Garkusha.\nUkraine, Dnipro\n\n");
	
	if(argc!=5)
	{
		fputs("Input parameters not found!\n", stderr);
		printHelp();

		fputs("\n", stderr);
		
		return 1;
	}
	
    GDALDatasetH  pSrcDataset = NULL;
    GDALDatasetH  pDstDataset = NULL;
    
    GDALRasterBandH pSrcBand = NULL;
    GDALRasterBandH pDstBand = NULL;
    
    GDALDriverH pDriver = NULL;

    GDALAllRegister();
	
	bool flagNoData = (atoi(argv[argc-1]) == 1)?true:false;
	int sensorIndexFlag = OLI;
	
	if( strcmp(argv[argc-2], "oli") == 0) 	sensorIndexFlag = OLI;
	else
	if( strcmp(argv[argc-2], "etm") == 0) 	sensorIndexFlag = ETM;
	else
	if( strcmp(argv[argc-2], "tm4") == 0) 	sensorIndexFlag = TM4;
	else
	if( strcmp(argv[argc-2], "tm5") == 0) 	sensorIndexFlag = TM5;
	else
	//if( strcmp(argv[argc-2], "msi10") == 0) sensorIndexFlag = S2AMSI10;
	//else
	if( strcmp(argv[argc-2], "msi") == 0) 	sensorIndexFlag = S2AMSI;
		    
    pSrcDataset = GDALOpen( argv[1], GA_ReadOnly );
    
    int bands = 0;
    
    if(pSrcDataset!=NULL)
    {
		if(CUtils::isFloat32DataType(pSrcDataset))
		{
			bands = GDALGetRasterCount(pSrcDataset);
			if( ((bands == 6)||(bands == 4)) )
			{
					pSrcBand = GDALGetRasterBand(pSrcDataset, 1);
					if(pSrcBand != NULL)
					{
							int cols  = GDALGetRasterBandXSize(pSrcBand);
							int rows  = GDALGetRasterBandYSize(pSrcBand);

							float NoDataValue = 0;

							pDriver = GDALGetDriverByName("GTiff");
							char **papszOptions = NULL;
							pDstDataset = GDALCreate(pDriver, argv[2], cols, rows, COUNT_OUT_BANDS, GDT_Float32, papszOptions);
							double adfGeoTransform[6]={0};
							GDALGetGeoTransform(pSrcDataset, adfGeoTransform );
							const char *szProjection = GDALGetProjectionRef(pSrcDataset);
							GDALSetGeoTransform(pDstDataset, adfGeoTransform );
							GDALSetProjection(pDstDataset, szProjection );
						
							pDstBand = GDALGetRasterBand(pDstDataset, 1);
						
							float *pSrcLine = NULL;
							float *pDstLine = NULL;
					
							pSrcLine = (float*)CPLMalloc(sizeof(GDALGetRasterDataType(pSrcBand))*cols);
							pDstLine = (float*)CPLMalloc(sizeof(GDALGetRasterDataType(pDstBand))*cols);
							
							
							if(flagNoData == false)
							{
								for(int resultBandNumber=1; resultBandNumber <= COUNT_OUT_BANDS; resultBandNumber++)
								{
									fprintf(stderr, "Processing for band %d...\n", resultBandNumber);
									
									pDstBand = GDALGetRasterBand(pDstDataset, resultBandNumber);

									int pr = CUtils::progress_ln_ex(stderr, 0, 0, START_PROGRESS);
									for(int i=0; i<rows; i++)
									{
										for(int j=0; j<cols; j++) pDstLine[j] = 0;
								
										for(int currentBandNumber=1; currentBandNumber <= bands; currentBandNumber++)
										{
											pSrcBand = GDALGetRasterBand(pSrcDataset, currentBandNumber);		

											GDALRasterIO(pSrcBand, GF_Read, 0, i, cols, 1, pSrcLine, cols, 1, GDALGetRasterDataType(pSrcBand), 0, 0 );
										
											for(int j=0; j<cols; j++) pDstLine[j] += getTasseledCapValue(pSrcLine[j], sensorIndexFlag, resultBandNumber, currentBandNumber);
										}
										
										if(sensorIndexFlag == TM5) for(int j=0; j<cols; j++) pDstLine[j] += TM5_TCCoeff[resultBandNumber][6];
										
										GDALRasterIO(pDstBand, GF_Write, 0, i, cols, 1, pDstLine, cols, 1, GDT_Float32, 0, 0 );
										
										pr = CUtils::progress_ln_ex(stderr, i, rows, pr);
									}
									CUtils::progress_ln_ex(stderr, 0, 0, END_PROGRESS);
								}
							}
							else // WITH NODATA VALUE - pixel(1,1)
							{
								for(int resultBandNumber=1; resultBandNumber <= COUNT_OUT_BANDS; resultBandNumber++)
								{
									fprintf(stderr, "Processing for band %d...\n", resultBandNumber);
									
									pDstBand = GDALGetRasterBand(pDstDataset, resultBandNumber);
									
									int pr = CUtils::progress_ln_ex(stderr, 0, 0, START_PROGRESS);
									for(int i=0; i<rows; i++)
									{
										for(int j=0; j<cols; j++) pDstLine[j] = 0;
								
										for(int currentBandNumber=1; currentBandNumber <= bands; currentBandNumber++)
										{
											pSrcBand = GDALGetRasterBand(pSrcDataset, currentBandNumber);		
											NoDataValue = CUtils::getFloatNoDataValueAsBackground(pSrcBand);
											
											GDALRasterIO(pSrcBand, GF_Read, 0, i, cols, 1, pSrcLine, cols, 1, GDALGetRasterDataType(pSrcBand), 0, 0 );
										
											for(int j=0; j<cols; j++) 
											{
												if(NoDataValue == pSrcLine[j]) pDstLine[j] = NoDataValue;
												else pDstLine[j] += getTasseledCapValue(pSrcLine[j], sensorIndexFlag, resultBandNumber, currentBandNumber);
											}
										}
										
										if(sensorIndexFlag == TM5)
										{
											for(int j=0; j<cols; j++) if(NoDataValue != pDstLine[j]) pDstLine[j] += TM5_TCCoeff[resultBandNumber][6];
										}
										
										GDALRasterIO(pDstBand, GF_Write, 0, i, cols, 1, pDstLine, cols, 1, GDT_Float32, 0, 0 );
										
										pr = CUtils::progress_ln_ex(stderr, i, rows, pr);
									}
									CUtils::progress_ln_ex(stderr, 0, 0, END_PROGRESS);
								}
							}
							
							CPLFree(pSrcLine); pSrcLine = NULL;
							CPLFree(pDstLine); pDstLine = NULL;
							
							if(flagNoData) CUtils::calculateFloatGeoTIFFStatistics(pDstDataset, -1, true);
							else CUtils::calculateFloatGeoTIFFStatistics(pDstDataset, -1, false);
							
							fputs("Output band:\n\tband1: Brightness, band2: Greenness (Vegetation), band3: Wetness, band4: Haze\n\n", stderr);
							fputs("\nEnd Processing.\n\n", stderr);
					}
			}
			else
			{
				fputs("\nERROR: Source Band Number is Invalid!!!\n", stderr);
				fprintf(stderr, "Source Bands Number: %d!\n\n", bands);
				printHelp();
			}
		}
		
		if(pSrcDataset!=NULL) { GDALClose(pSrcDataset); }
		if(pDstDataset!=NULL) { GDALClose(pDstDataset); }
	}

    return 0;
}
示例#18
0
int main( int argc, char ** argv )

{
    const char *pszSrcFilename = NULL;
    int anReqOverviews[1000];
    int nReqOverviewCount = 0;
    bool bMasks = false;

    GDALAllRegister();

    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );

/* -------------------------------------------------------------------- */
/*      Process arguments.                                              */
/* -------------------------------------------------------------------- */
    for( int iArg = 1; iArg < argc; iArg++ )
    {
        if( EQUAL(argv[iArg],"-masks") )
        {
            bMasks = true;
        }
        else if( pszSrcFilename == NULL )
        {
            pszSrcFilename = argv[iArg];
        }
        else if( atoi(argv[iArg]) > 0 || EQUAL(argv[iArg],"0") )
        {
            anReqOverviews[nReqOverviewCount++] = atoi(argv[iArg]);
        }
        else
        {
            Usage();
        }
    }

    if( pszSrcFilename == NULL )
        Usage();

/* -------------------------------------------------------------------- */
/*      Open the input file.                                            */
/* -------------------------------------------------------------------- */
    GDALDatasetH hSrcDS = GDALOpen( pszSrcFilename, GA_ReadOnly );

    if( hSrcDS == NULL )
        exit( 1 );

/* ==================================================================== */
/*      Process all bands.                                              */
/* ==================================================================== */
    int iBand;
    int nBandCount = GDALGetRasterCount( hSrcDS );

    for( iBand = 0; iBand < nBandCount; iBand++ )
    {
        GDALRasterBandH hBaseBand = GDALGetRasterBand( hSrcDS, iBand+1 );

/* -------------------------------------------------------------------- */
/*      Process all overviews.                                          */
/* -------------------------------------------------------------------- */
        int iOverview;
        int nOverviewCount = GDALGetOverviewCount( hBaseBand );

        for( iOverview = 0; iOverview < nOverviewCount; iOverview++ )
        {
            GDALRasterBandH hSrcOver = GDALGetOverview( hBaseBand, iOverview );

            if (hSrcOver == NULL)
            {
                fprintf(stderr, "skipping overview %d as being null\n", iOverview);
                continue;
            }

/* -------------------------------------------------------------------- */
/*      Is this a requested overview?                                   */
/* -------------------------------------------------------------------- */
            if( nReqOverviewCount > 0 )
            {
                int i; 

                for( i = 0; i < nReqOverviewCount; i++ )
                {
                    if( anReqOverviews[i] == iOverview )
                        break;
                }

                if( i == nReqOverviewCount )
                    continue;
            }

/* -------------------------------------------------------------------- */
/*      Create matching output file.                                    */
/* -------------------------------------------------------------------- */
            CPLString osFilename;
            osFilename.Printf( "%s_%d_%d.tif",
                               CPLGetBasename(pszSrcFilename),
                               iBand+1, iOverview );
            DumpBand( hSrcDS, hSrcOver, osFilename );

            if( bMasks )
            {
                CPLString osFilename;
                osFilename.Printf( "%s_%d_%d_mask.tif",
                                CPLGetBasename(pszSrcFilename),
                                iBand+1, iOverview );
                DumpBand( hSrcDS, GDALGetMaskBand(hSrcOver), osFilename );
            }
        }

/* -------------------------------------------------------------------- */
/*      Do we dump the mask?                                            */
/* -------------------------------------------------------------------- */
        if( bMasks )
        {
            CPLString osFilename;
            osFilename.Printf( "%s_%d_mask.tif",
                               CPLGetBasename(pszSrcFilename),
                               iBand+1 );
            DumpBand( hSrcDS, GDALGetMaskBand(hBaseBand), osFilename );
        }
    }

    GDALClose( hSrcDS );

    CSLDestroy( argv );
    GDALDestroyDriverManager();

    return 0;
}
示例#19
0
static GDALDatasetH 
GDALWarpCreateOutput( GDALDatasetH hSrcDS, const char *pszFilename, 
                      const char *pszFormat, const char *pszSourceSRS, 
                      const char *pszTargetSRS, int nOrder,
                      char **papszCreateOptions )

{
    GDALDriverH hDriver;
    GDALDatasetH hDstDS;
    void *hTransformArg;
    double adfDstGeoTransform[6];
    int nPixels=0, nLines=0;
    GDALColorTableH hCT;

/* -------------------------------------------------------------------- */
/*      Find the output driver.                                         */
/* -------------------------------------------------------------------- */
    hDriver = GDALGetDriverByName( pszFormat );
    if( hDriver == NULL 
        || GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) == NULL )
    {
        int	iDr;
        
        printf( "Output driver `%s' not recognised or does not support\n", 
                pszFormat );
        printf( "direct output file creation.  The following format drivers are configured\n"
                "and support direct output:\n" );

        for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ )
        {
            GDALDriverH hDriver = GDALGetDriver(iDr);

            if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL) != NULL )
            {
                printf( "  %s: %s\n",
                        GDALGetDriverShortName( hDriver  ),
                        GDALGetDriverLongName( hDriver ) );
            }
        }
        printf( "\n" );
        exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      Create a transformation object from the source to               */
/*      destination coordinate system.                                  */
/* -------------------------------------------------------------------- */
    hTransformArg = 
        GDALCreateGenImgProjTransformer( hSrcDS, pszSourceSRS, 
                                         NULL, pszTargetSRS, 
                                         TRUE, 1000.0, nOrder );

    if( hTransformArg == NULL )
        return NULL;

/* -------------------------------------------------------------------- */
/*      Get approximate output definition.                              */
/* -------------------------------------------------------------------- */
    if( GDALSuggestedWarpOutput( hSrcDS, 
                                 GDALGenImgProjTransform, hTransformArg, 
                                 adfDstGeoTransform, &nPixels, &nLines )
        != CE_None )
        return NULL;

    GDALDestroyGenImgProjTransformer( hTransformArg );

/* -------------------------------------------------------------------- */
/*      Did the user override some parameters?                          */
/* -------------------------------------------------------------------- */
    if( dfXRes != 0.0 && dfYRes != 0.0 )
    {
        CPLAssert( nPixels == 0 && nLines == 0 );
        if( dfMinX == 0.0 && dfMinY == 0.0 && dfMaxX == 0.0 && dfMaxY == 0.0 )
        {
            dfMinX = adfDstGeoTransform[0];
            dfMaxX = adfDstGeoTransform[0] + adfDstGeoTransform[1] * nPixels;
            dfMaxY = adfDstGeoTransform[3];
            dfMinY = adfDstGeoTransform[3] + adfDstGeoTransform[5] * nLines;
        }

        nPixels = (int) ((dfMaxX - dfMinX + (dfXRes/2.0)) / dfXRes);
        nLines = (int) ((dfMaxY - dfMinY + (dfYRes/2.0)) / dfYRes);
        adfDstGeoTransform[0] = dfMinX;
        adfDstGeoTransform[3] = dfMaxY;
        adfDstGeoTransform[1] = dfXRes;
        adfDstGeoTransform[5] = -dfYRes;
    }

    else if( nForcePixels != 0 && nForceLines != 0 )
    {
        if( dfMinX == 0.0 && dfMinY == 0.0 && dfMaxX == 0.0 && dfMaxY == 0.0 )
        {
            dfMinX = adfDstGeoTransform[0];
            dfMaxX = adfDstGeoTransform[0] + adfDstGeoTransform[1] * nPixels;
            dfMaxY = adfDstGeoTransform[3];
            dfMinY = adfDstGeoTransform[3] + adfDstGeoTransform[5] * nLines;
        }

        dfXRes = (dfMaxX - dfMinX) / nForcePixels;
        dfYRes = (dfMaxY - dfMinY) / nForceLines;

        adfDstGeoTransform[0] = dfMinX;
        adfDstGeoTransform[3] = dfMaxY;
        adfDstGeoTransform[1] = dfXRes;
        adfDstGeoTransform[5] = -dfYRes;

        nPixels = nForcePixels;
        nLines = nForceLines;
    }

    else if( dfMinX != 0.0 || dfMinY != 0.0 || dfMaxX != 0.0 || dfMaxY != 0.0 )
    {
        dfXRes = adfDstGeoTransform[1];
        dfYRes = fabs(adfDstGeoTransform[5]);

        nPixels = (int) ((dfMaxX - dfMinX + (dfXRes/2.0)) / dfXRes);
        nLines = (int) ((dfMaxY - dfMinY + (dfYRes/2.0)) / dfYRes);

        adfDstGeoTransform[0] = dfMinX;
        adfDstGeoTransform[3] = dfMaxY;
    }

/* -------------------------------------------------------------------- */
/*      Create the output file.                                         */
/* -------------------------------------------------------------------- */
    printf( "Creating output file is that %dP x %dL.\n", nPixels, nLines );

    hDstDS = GDALCreate( hDriver, pszFilename, nPixels, nLines, 
                         GDALGetRasterCount(hSrcDS),
                         GDALGetRasterDataType(GDALGetRasterBand(hSrcDS,1)),
                         papszCreateOptions );

    if( hDstDS == NULL )
        return NULL;

/* -------------------------------------------------------------------- */
/*      Write out the projection definition.                            */
/* -------------------------------------------------------------------- */
    GDALSetProjection( hDstDS, pszTargetSRS );
    GDALSetGeoTransform( hDstDS, adfDstGeoTransform );

/* -------------------------------------------------------------------- */
/*      Copy the color table, if required.                              */
/* -------------------------------------------------------------------- */
    hCT = GDALGetRasterColorTable( GDALGetRasterBand(hSrcDS,1) );
    if( hCT != NULL )
        GDALSetRasterColorTable( GDALGetRasterBand(hDstDS,1), hCT );

    return hDstDS;
}
示例#20
0
static gint print_handler( void * cb_data, void * scanline_in )

{
    unsigned char *scanline = (unsigned char *) scanline_in;
    static GDALDatasetH  working_ds = NULL;
    static int next_scanline = 0;
    static GDALRasterBandH red_band, green_band, blue_band;
    gint   width;

    if( cb_data == NULL && scanline_in == NULL )
    {
        next_scanline = 0;
        working_ds = NULL;
        return -1;
    }

    if( working_ds != cb_data )
    {
        working_ds = (GDALDatasetH) cb_data;
        next_scanline = 0;

        red_band = GDALGetRasterBand( working_ds, 1 );
        if( GDALGetRasterCount( working_ds ) >= 3 )
        {
            green_band = GDALGetRasterBand( working_ds, 2 );
            blue_band = GDALGetRasterBand( working_ds, 3 );
        }
        else
        {
            green_band = blue_band = NULL;
        }

        if( red_band == NULL )
            return -1;
    }

    width = GDALGetRasterXSize( working_ds );

    if( green_band == NULL )
    {
        GByte	*grey;
        int     i, value;

        grey = g_new( GByte, width );
        
        for( i = 0; i < width; i++ )
        {
            value = *(scanline++);
            value += *(scanline++);
            value += *(scanline++);
            value = (value+1) / 3;
            grey[i] = value;
        }
        
        GDALRasterIO( red_band, GF_Write, 0, next_scanline, width, 1, 
                      grey, width, 1, GDT_Byte, 1, 0 );
        g_free( grey );
    }
    else
    {
        GDALRasterIO( red_band, GF_Write, 0, next_scanline, width, 1, 
                      scanline+0, width, 1, GDT_Byte, 3, 0 );
        GDALRasterIO( green_band, GF_Write, 0, next_scanline, width, 1, 
                      scanline+1, width, 1, GDT_Byte, 3, 0 );
        GDALRasterIO( blue_band, GF_Write, 0, next_scanline, width, 1, 
                      scanline+2, width, 1, GDT_Byte, 3, 0 );
    }
    
    next_scanline++;

    return 0;
}
示例#21
0
bool QgsAlignRaster::createAndWarp( const Item& raster )
{
  GDALDriverH hDriver = GDALGetDriverByName( "GTiff" );
  if ( !hDriver )
  {
    mErrorMessage = QString( "GDALGetDriverByName(GTiff) failed." );
    return false;
  }

  // Open the source file.
  GDALDatasetH hSrcDS = GDALOpen( raster.inputFilename.toLocal8Bit().constData(), GA_ReadOnly );
  if ( !hSrcDS )
  {
    mErrorMessage = QObject::tr( "Unable to open input file: " ) + raster.inputFilename;
    return false;
  }

  // Create output with same datatype as first input band.

  int bandCount = GDALGetRasterCount( hSrcDS );
  GDALDataType eDT = GDALGetRasterDataType( GDALGetRasterBand( hSrcDS, 1 ) );

  // Create the output file.
  GDALDatasetH hDstDS;
  hDstDS = GDALCreate( hDriver, raster.outputFilename.toLocal8Bit().constData(), mXSize, mYSize,
                       bandCount, eDT, NULL );
  if ( !hDstDS )
  {
    GDALClose( hSrcDS );
    mErrorMessage = QObject::tr( "Unable to create output file: " ) + raster.outputFilename;
    return false;
  }

  // Write out the projection definition.
  GDALSetProjection( hDstDS, mCrsWkt.toAscii().constData() );
  GDALSetGeoTransform( hDstDS, ( double* )mGeoTransform );

  // Copy the color table, if required.
  GDALColorTableH hCT = GDALGetRasterColorTable( GDALGetRasterBand( hSrcDS, 1 ) );
  if ( hCT != NULL )
    GDALSetRasterColorTable( GDALGetRasterBand( hDstDS, 1 ), hCT );

  // -----------------------------------------------------------------------

  // Setup warp options.
  GDALWarpOptions* psWarpOptions = GDALCreateWarpOptions();
  psWarpOptions->hSrcDS = hSrcDS;
  psWarpOptions->hDstDS = hDstDS;

  psWarpOptions->nBandCount = GDALGetRasterCount( hSrcDS );
  psWarpOptions->panSrcBands = ( int * ) CPLMalloc( sizeof( int ) * psWarpOptions->nBandCount );
  psWarpOptions->panDstBands = ( int * ) CPLMalloc( sizeof( int ) * psWarpOptions->nBandCount );
  for ( int i = 0; i < psWarpOptions->nBandCount; ++i )
  {
    psWarpOptions->panSrcBands[i] = i + 1;
    psWarpOptions->panDstBands[i] = i + 1;
  }

  psWarpOptions->eResampleAlg = ( GDALResampleAlg ) raster.resampleMethod;

  // our progress function
  psWarpOptions->pfnProgress = _progress;
  psWarpOptions->pProgressArg = this;

  // Establish reprojection transformer.
  psWarpOptions->pTransformerArg =
    GDALCreateGenImgProjTransformer( hSrcDS, GDALGetProjectionRef( hSrcDS ),
                                     hDstDS, GDALGetProjectionRef( hDstDS ),
                                     FALSE, 0.0, 1 );
  psWarpOptions->pfnTransformer = GDALGenImgProjTransform;

  double rescaleArg[2];
  if ( raster.rescaleValues )
  {
    rescaleArg[0] = raster.srcCellSizeInDestCRS; // source cell size
    rescaleArg[1] = mCellSizeX * mCellSizeY;  // destination cell size
    psWarpOptions->pfnPreWarpChunkProcessor = rescalePreWarpChunkProcessor;
    psWarpOptions->pfnPostWarpChunkProcessor = rescalePostWarpChunkProcessor;
    psWarpOptions->pPreWarpProcessorArg = rescaleArg;
    psWarpOptions->pPostWarpProcessorArg = rescaleArg;
    // force use of float32 data type as that is what our pre/post-processor uses
    psWarpOptions->eWorkingDataType = GDT_Float32;
  }

  // Initialize and execute the warp operation.
  GDALWarpOperation oOperation;
  oOperation.Initialize( psWarpOptions );
  oOperation.ChunkAndWarpImage( 0, 0, mXSize, mYSize );

  GDALDestroyGenImgProjTransformer( psWarpOptions->pTransformerArg );
  GDALDestroyWarpOptions( psWarpOptions );

  GDALClose( hDstDS );
  GDALClose( hSrcDS );
  return true;
}
示例#22
0
//相对辐射校正 相对辐射校正是不是就是非均匀性校正
long QPDLevel1Process::Level1Proc_RadiationRelative(const char* pathImg, const char* pathImgRad, const char* pathRelRegFile)
{
	CPLSetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");	//中文路径
	GDALAllRegister();
	long lError = 0;
	unsigned short *imgBuffeSrc = NULL;	//影像数据
	unsigned short *imgBuffeDst = NULL;	//影像数据
	float* parametersA = NULL, *parametersB = NULL, *parametersAux = NULL;//校正系数
	float* parametersSgn = NULL;
	GDALDatasetH m_dataset = GDALOpen(pathImg, GA_ReadOnly);
	int xsize = GDALGetRasterXSize(m_dataset);
	int ysize = GDALGetRasterYSize(m_dataset);
	int bands = GDALGetRasterCount(m_dataset);

	//char **papszOptions = NULL;
	//papszOptions = CSLSetNameValue(papszOptions, "INTERLEAVE", "BAND");
	//GDALDatasetH m_datasetdst = GDALCreate(GDALGetDriverByName("GTiff"), pathImgRad, xsize, ysize, bands, GDT_UInt16, papszOptions);
	FILE* fDst = NULL;
	if (fopen_s(&fDst, pathImgRad, "wb") != 0)
		exit(-1);
	int nSamples, nBands,nLevels;
	LevelProc_GetParameterInfo(pathRelRegFile, nSamples, nBands, nLevels);

	//数据空间申请
	try
	{
		imgBuffeSrc = new unsigned short[xsize*ysize];
		imgBuffeDst = new unsigned short[xsize*ysize];
		parametersA = new float[nSamples*nBands*(nLevels-1)];
		parametersB = new float[nSamples*nBands*(nLevels-1)];
		parametersAux = new float[nLevels*nBands];
		parametersSgn = new float[nSamples*nBands];
	}
	catch (bad_alloc)
	{
		printf("allocate memory error\n");
		exit(-1);
	}

	if (LevelProc_RelativeParameters(pathRelRegFile, parametersA, parametersB, parametersAux) != 0)
		exit(-1);//读取校正参数异常
	
	//根据nLevel进行校正
	//线性校正
	if (nLevels == 2)
	{
		for (int i = 0; i < bands; ++i)
		{
			printf("process bands:%d\n", i + 1);
			GDALRasterIO(GDALGetRasterBand(m_dataset, i + 1), GF_Read, 0, 0, xsize, ysize, imgBuffeSrc, xsize, ysize, GDT_UInt16, 0, 0);
			for (int j = 0; j < xsize; ++j)
			{
				for (int k = 0; k < ysize; ++k)
				{
					int nImgOffset = k*nSamples + j;
					int nCofOffset = i*nSamples + j;
					imgBuffeDst[nImgOffset] = unsigned short(imgBuffeSrc[nImgOffset] * parametersA[nCofOffset] + parametersB[nCofOffset]);
					parametersSgn[i*nSamples + j] = parametersA[nCofOffset];
				}
			}
			//如果需要进行坏线校正的话
			for (int j = 0; j < nSamples; ++j)
			{
				//第i个波段第j个探元
				int		nFlagA = -1, nFlagB = -1;
				float	fWeightA = 0, fWeightB = 0;
				int		nCofOffset = i*nSamples + j;

				if (parametersSgn[nCofOffset] == 0)
				{
					if (j == 0)
					{
						for (int n = 1; n<nSamples; n++)
						{
							if (parametersSgn[nCofOffset + n] != 0)
							{
								nFlagB = j + n;
								fWeightA = 0;
								fWeightB = 1;
								break;
							}
						}
						nFlagA = -1;
					}
					else if (j == nSamples - 1)
					{
						for (int m = 1; m <= j; m++)
						{
							if (parametersSgn[nCofOffset - m] != 0)
							{
								nFlagA = j - m;
								fWeightA = 1;
								fWeightB = 0;
								break;
							}
						}
						nFlagB = -1;
					}
					else
					{
						for (int m = 1; m <= j; m++)
						{
							if (parametersSgn[nCofOffset - m] != 0 && j - m >= 0)
							{
								nFlagA = j - m;
								break;
							}
						}
						for (int n = 1; n <= nSamples - j; n++)
						{
							if (parametersSgn[nCofOffset + n] != 0 && j + n<nSamples)
							{
								nFlagB = j + n;
								break;
							}
						}
						if (nFlagA != -1 && nFlagB != -1)
						{
							fWeightA = (float)(j - nFlagA) / (float)(nFlagB - nFlagA);
							fWeightB = (float)(nFlagB - j) / (float)(nFlagB - nFlagA);
						}
						if (nFlagA == -1 && nFlagB != -1)
						{
							fWeightA = 0;
							fWeightB = 1;
						}
						if (nFlagA != -1 && nFlagB == -1)
						{
							fWeightA = 1;
							fWeightB = 0;
						}
					}
					if (nFlagA != -1 && nFlagB != -1)
					{
						for (int k = 0; k<ysize; k++)
						{
							imgBuffeDst[k*nSamples + j] = unsigned short(imgBuffeDst[k*nSamples + nFlagA] * fWeightA + imgBuffeDst[k*nSamples + nFlagB] * fWeightB);
						}
					}
					else if (nFlagA == -1 && nFlagB != -1)
					{
						for (int k = 0; k<ysize; k++)
						{
							imgBuffeDst[k*nSamples + j] = imgBuffeDst[k*nSamples + nFlagB];
						}
					}
					else
					{
						for (int k = 0; k<ysize; k++)
						{
							imgBuffeDst[k*nSamples + j] = imgBuffeDst[k*nSamples + nFlagA];
						}
					}
				}
			}
			//数据输出
			fwrite(imgBuffeDst, 2, xsize*ysize, fDst);
			fflush(fDst);
			//GDALRasterIO(GDALGetRasterBand(m_datasetdst, i + 1), GF_Read, 0, 0, xsize, ysize, imgBuffeDst, xsize, ysize, GDT_UInt16, 0, 0);
		}
	}
示例#23
0
void CUtils::calculateByteGeoTIFFStatistics(GDALDatasetH hDataset, int userBandNumber, byte flNoDataValueAsBackground, byte NoDataValue)
{
	fputs("\nCalculate statistics...\n", stderr);

	GDALRasterBandH hBand =  GDALGetRasterBand(hDataset, 1);
	int cols  = GDALGetRasterBandXSize(hBand);
	int rows  = GDALGetRasterBandYSize(hBand);
	int bands = GDALGetRasterCount(hDataset);
	
	byte * pbuf = NULL;
	pbuf = (byte *)CPLMalloc(sizeof(byte)*cols);
	
	byte min = 0, max = 0, mean = 0;
	double stddev = 0;
    double summ = 0;
    int count = 0;
	
	for(int band=1; band<=bands; band++)
	{
		if(userBandNumber != -1) fprintf(stderr, "Band %d...\n", userBandNumber);
		else fprintf(stderr, "Band %d...\n", band);
		
		hBand =  GDALGetRasterBand(hDataset, band);		
		if(flNoDataValueAsBackground) NoDataValue = getFloatNoDataValueAsBackground(hBand);
		
		min = max = mean = stddev = summ = 0;
		count = 0;
		bool flFirst = true;
		
		int pr = CUtils::progress_ln_ex(stderr, 0, 0, START_PROGRESS);
		for(int i=0; i<rows; i++)
		{
			GDALRasterIO(hBand, GF_Read, 0, i, cols, 1, pbuf, cols, 1, GDT_Byte, 0, 0 );
			for(int j=0; j<cols; j++) if(pbuf[j]!=NoDataValue) 
			{
				if(flFirst)
				{
					mean = pbuf[j];
					min = max = mean;
					flFirst = false;
				}
				else
				{
					mean += pbuf[j];
					if( min > pbuf[j] ) min = pbuf[j];
					if( max < pbuf[j] ) max = pbuf[j];
				}
				count++;
			}
			pr = CUtils::progress_ln_ex(stderr, i, rows, pr);
		}
		CUtils::progress_ln_ex(stderr, 0, 0, END_PROGRESS);
		
		double dmean = 0;
		if(count > 0) dmean = mean / (double)count;
		
		pr = CUtils::progress_ln_ex(stderr, 0, 0, START_PROGRESS);
		for(int i=0; i<rows; i++)
		{
			GDALRasterIO(hBand, GF_Read, 0, i, cols, 1, pbuf, cols, 1, GDT_Byte, 0, 0 );
			for(int j=0; j<cols; j++) if(pbuf[j]!=NoDataValue) summ += ((double)pbuf[j]-dmean)*((double)pbuf[j]-dmean);
						
			pr = CUtils::progress_ln_ex(stderr, i, rows, pr);
		}
		CUtils::progress_ln_ex(stderr, 0, 0, END_PROGRESS);
		
		summ = 0; stddev = 0;
		if((count-1)>0)
		{
			summ /= (double)(count-1);
			if(summ!=0) stddev = sqrt(summ);
		}
			
		GDALSetRasterStatistics(hBand, min, max, mean, stddev);
		GDALSetRasterNoDataValue(hBand, NoDataValue);
	}
	
	CPLFree(pbuf);
}
示例#24
0
/** GDALComputeMatchingPoints. TODO document */
GDAL_GCP CPL_DLL *
GDALComputeMatchingPoints( GDALDatasetH hFirstImage,
                           GDALDatasetH hSecondImage,
                           char **papszOptions,
                           int *pnGCPCount )
{
    *pnGCPCount = 0;

/* -------------------------------------------------------------------- */
/*      Override default algorithm parameters.                          */
/* -------------------------------------------------------------------- */
    int nOctaveStart, nOctaveEnd;
    double dfSURFThreshold;

    nOctaveStart =atoi(CSLFetchNameValueDef(papszOptions, "OCTAVE_START", "2"));
    nOctaveEnd = atoi(CSLFetchNameValueDef(papszOptions, "OCTAVE_END", "2"));

    dfSURFThreshold = CPLAtof(
        CSLFetchNameValueDef(papszOptions, "SURF_THRESHOLD", "0.001"));
    const double dfMatchingThreshold = CPLAtof(
        CSLFetchNameValueDef(papszOptions, "MATCHING_THRESHOLD", "0.015"));

/* -------------------------------------------------------------------- */
/*      Identify the bands to use.  For now we are effectively          */
/*      limited to using RGB input so if we have one band only treat    */
/*      it as red=green=blue=band 1.  Disallow non eightbit imagery.    */
/* -------------------------------------------------------------------- */
    int anBandMap1[3] = { 1, 1, 1 };
    if( GDALGetRasterCount(hFirstImage) >= 3 )
    {
        anBandMap1[1] = 2;
        anBandMap1[2] = 3;
    }

    int anBandMap2[3] = { 1, 1, 1 };
    if( GDALGetRasterCount(hSecondImage) >= 3 )
    {
        anBandMap2[1] = 2;
        anBandMap2[2] = 3;
    }

/* -------------------------------------------------------------------- */
/*      Collect reference points on each image.                         */
/* -------------------------------------------------------------------- */
    std::vector<GDALFeaturePoint> *poFPCollection1 =
        GatherFeaturePoints(reinterpret_cast<GDALDataset *>(hFirstImage),
                            anBandMap1,
                            nOctaveStart, nOctaveEnd, dfSURFThreshold);
    if( poFPCollection1 == nullptr )
        return nullptr;

    std::vector<GDALFeaturePoint> *poFPCollection2 =
        GatherFeaturePoints(reinterpret_cast<GDALDataset *>(hSecondImage),
                            anBandMap2,
                            nOctaveStart, nOctaveEnd,
                            dfSURFThreshold);

    if( poFPCollection2 == nullptr )
    {
        delete poFPCollection1;
        return nullptr;
    }

/* -------------------------------------------------------------------- */
/*      Try to find corresponding locations.                            */
/* -------------------------------------------------------------------- */
    std::vector<GDALFeaturePoint *> oMatchPairs;

    if( CE_None != GDALSimpleSURF::MatchFeaturePoints(
        &oMatchPairs, poFPCollection1, poFPCollection2,
        dfMatchingThreshold ))
    {
        delete poFPCollection1;
        delete poFPCollection2;
        return nullptr;
    }

    *pnGCPCount = static_cast<int>(oMatchPairs.size()) / 2;

/* -------------------------------------------------------------------- */
/*      Translate these into GCPs - but with the output coordinate      */
/*      system being pixel/line on the second image.                    */
/* -------------------------------------------------------------------- */
    GDAL_GCP *pasGCPList =
        static_cast<GDAL_GCP*>(CPLCalloc(*pnGCPCount, sizeof(GDAL_GCP)));

    GDALInitGCPs(*pnGCPCount, pasGCPList);

    for( int i=0; i < *pnGCPCount; i++ )
    {
        GDALFeaturePoint *poPoint1 = oMatchPairs[i*2  ];
        GDALFeaturePoint *poPoint2 = oMatchPairs[i*2+1];

        pasGCPList[i].dfGCPPixel = poPoint1->GetX() + 0.5;
        pasGCPList[i].dfGCPLine = poPoint1->GetY() + 0.5;

        pasGCPList[i].dfGCPX = poPoint2->GetX() + 0.5;
        pasGCPList[i].dfGCPY = poPoint2->GetY() + 0.5;
        pasGCPList[i].dfGCPZ = 0.0;
    }

    // Cleanup the feature point lists.
    delete poFPCollection1;
    delete poFPCollection2;

/* -------------------------------------------------------------------- */
/*      Optionally transform into the georef coordinates of the         */
/*      output image.                                                   */
/* -------------------------------------------------------------------- */
    const bool bGeorefOutput =
        CPLTestBool(CSLFetchNameValueDef(papszOptions, "OUTPUT_GEOREF", "NO"));

    if( bGeorefOutput )
    {
        double adfGeoTransform[6] = {};

        GDALGetGeoTransform( hSecondImage, adfGeoTransform );

        for( int i=0; i < *pnGCPCount; i++ )
        {
            GDALApplyGeoTransform(adfGeoTransform,
                                  pasGCPList[i].dfGCPX,
                                  pasGCPList[i].dfGCPY,
                                  &(pasGCPList[i].dfGCPX),
                                  &(pasGCPList[i].dfGCPY));
        }
    }

    return pasGCPList;
}
示例#25
0
int QgsZonalStatistics::calculateStatistics( QProgressDialog* p )
{
  if ( !mPolygonLayer || mPolygonLayer->geometryType() != QGis::Polygon )
  {
    return 1;
  }

  QgsVectorDataProvider* vectorProvider = mPolygonLayer->dataProvider();
  if ( !vectorProvider )
  {
    return 2;
  }

  //open the raster layer and the raster band
  GDALAllRegister();
  GDALDatasetH inputDataset = GDALOpen( TO8F( mRasterFilePath ), GA_ReadOnly );
  if ( !inputDataset )
  {
    return 3;
  }

  if ( GDALGetRasterCount( inputDataset ) < ( mRasterBand - 1 ) )
  {
    GDALClose( inputDataset );
    return 4;
  }

  GDALRasterBandH rasterBand = GDALGetRasterBand( inputDataset, mRasterBand );
  if ( !rasterBand )
  {
    GDALClose( inputDataset );
    return 5;
  }
  mInputNodataValue = GDALGetRasterNoDataValue( rasterBand, nullptr );

  //get geometry info about raster layer
  int nCellsXGDAL = GDALGetRasterXSize( inputDataset );
  int nCellsYGDAL = GDALGetRasterYSize( inputDataset );
  double geoTransform[6];
  if ( GDALGetGeoTransform( inputDataset, geoTransform ) != CE_None )
  {
    GDALClose( inputDataset );
    return 6;
  }
  double cellsizeX = geoTransform[1];
  if ( cellsizeX < 0 )
  {
    cellsizeX = -cellsizeX;
  }
  double cellsizeY = geoTransform[5];
  if ( cellsizeY < 0 )
  {
    cellsizeY = -cellsizeY;
  }
  QgsRectangle rasterBBox( geoTransform[0], geoTransform[3] - ( nCellsYGDAL * cellsizeY ),
                           geoTransform[0] + ( nCellsXGDAL * cellsizeX ), geoTransform[3] );

  //add the new fields to the provider
  QList<QgsField> newFieldList;
  QString countFieldName;
  if ( mStatistics & QgsZonalStatistics::Count )
  {
    countFieldName = getUniqueFieldName( mAttributePrefix + "count" );
    QgsField countField( countFieldName, QVariant::Double, "double precision" );
    newFieldList.push_back( countField );
  }
  QString sumFieldName;
  if ( mStatistics & QgsZonalStatistics::Sum )
  {
    sumFieldName = getUniqueFieldName( mAttributePrefix + "sum" );
    QgsField sumField( sumFieldName, QVariant::Double, "double precision" );
    newFieldList.push_back( sumField );
  }
  QString meanFieldName;
  if ( mStatistics & QgsZonalStatistics::Mean )
  {
    meanFieldName = getUniqueFieldName( mAttributePrefix + "mean" );
    QgsField meanField( meanFieldName, QVariant::Double, "double precision" );
    newFieldList.push_back( meanField );
  }
  QString medianFieldName;
  if ( mStatistics & QgsZonalStatistics::Median )
  {
    medianFieldName = getUniqueFieldName( mAttributePrefix + "median" );
    QgsField medianField( medianFieldName, QVariant::Double, "double precision" );
    newFieldList.push_back( medianField );
  }
  QString stdevFieldName;
  if ( mStatistics & QgsZonalStatistics::StDev )
  {
    stdevFieldName = getUniqueFieldName( mAttributePrefix + "stdev" );
    QgsField stdField( stdevFieldName, QVariant::Double, "double precision" );
    newFieldList.push_back( stdField );
  }
  QString minFieldName;
  if ( mStatistics & QgsZonalStatistics::Min )
  {
    minFieldName = getUniqueFieldName( mAttributePrefix + "min" );
    QgsField minField( minFieldName, QVariant::Double, "double precision" );
    newFieldList.push_back( minField );
  }
  QString maxFieldName;
  if ( mStatistics & QgsZonalStatistics::Max )
  {
    maxFieldName = getUniqueFieldName( mAttributePrefix + "max" );
    QgsField maxField( maxFieldName, QVariant::Double, "double precision" );
    newFieldList.push_back( maxField );
  }
  QString rangeFieldName;
  if ( mStatistics & QgsZonalStatistics::Range )
  {
    rangeFieldName = getUniqueFieldName( mAttributePrefix + "range" );
    QgsField rangeField( rangeFieldName, QVariant::Double, "double precision" );
    newFieldList.push_back( rangeField );
  }
  QString minorityFieldName;
  if ( mStatistics & QgsZonalStatistics::Minority )
  {
    minorityFieldName = getUniqueFieldName( mAttributePrefix + "minority" );
    QgsField minorityField( minorityFieldName, QVariant::Double, "double precision" );
    newFieldList.push_back( minorityField );
  }
  QString majorityFieldName;
  if ( mStatistics & QgsZonalStatistics::Majority )
  {
    majorityFieldName = getUniqueFieldName( mAttributePrefix + "majority" );
    QgsField majField( majorityFieldName, QVariant::Double, "double precision" );
    newFieldList.push_back( majField );
  }
  QString varietyFieldName;
  if ( mStatistics & QgsZonalStatistics::Variety )
  {
    varietyFieldName = getUniqueFieldName( mAttributePrefix + "variety" );
    QgsField varietyField( varietyFieldName, QVariant::Int, "int" );
    newFieldList.push_back( varietyField );
  }
  vectorProvider->addAttributes( newFieldList );

  //index of the new fields
  int countIndex = mStatistics & QgsZonalStatistics::Count ? vectorProvider->fieldNameIndex( countFieldName ) : -1;
  int sumIndex = mStatistics & QgsZonalStatistics::Sum ? vectorProvider->fieldNameIndex( sumFieldName ) : -1;
  int meanIndex = mStatistics & QgsZonalStatistics::Mean ? vectorProvider->fieldNameIndex( meanFieldName ) : -1;
  int medianIndex = mStatistics & QgsZonalStatistics::Median ? vectorProvider->fieldNameIndex( medianFieldName ) : -1;
  int stdevIndex = mStatistics & QgsZonalStatistics::StDev ? vectorProvider->fieldNameIndex( stdevFieldName ) : -1;
  int minIndex = mStatistics & QgsZonalStatistics::Min ? vectorProvider->fieldNameIndex( minFieldName ) : -1;
  int maxIndex = mStatistics & QgsZonalStatistics::Max ? vectorProvider->fieldNameIndex( maxFieldName ) : -1;
  int rangeIndex = mStatistics & QgsZonalStatistics::Range ? vectorProvider->fieldNameIndex( rangeFieldName ) : -1;
  int minorityIndex = mStatistics & QgsZonalStatistics::Minority ? vectorProvider->fieldNameIndex( minorityFieldName ) : -1;
  int majorityIndex = mStatistics & QgsZonalStatistics::Majority ? vectorProvider->fieldNameIndex( majorityFieldName ) : -1;
  int varietyIndex = mStatistics & QgsZonalStatistics::Variety ? vectorProvider->fieldNameIndex( varietyFieldName ) : -1;

  if (( mStatistics & QgsZonalStatistics::Count && countIndex == -1 )
      || ( mStatistics & QgsZonalStatistics::Sum && sumIndex == -1 )
      || ( mStatistics & QgsZonalStatistics::Mean && meanIndex == -1 )
      || ( mStatistics & QgsZonalStatistics::Median && medianIndex == -1 )
      || ( mStatistics & QgsZonalStatistics::StDev && stdevIndex == -1 )
      || ( mStatistics & QgsZonalStatistics::Min && minIndex == -1 )
      || ( mStatistics & QgsZonalStatistics::Max && maxIndex == -1 )
      || ( mStatistics & QgsZonalStatistics::Range && rangeIndex == -1 )
      || ( mStatistics & QgsZonalStatistics::Minority && minorityIndex == -1 )
      || ( mStatistics & QgsZonalStatistics::Majority && majorityIndex == -1 )
      || ( mStatistics & QgsZonalStatistics::Variety && varietyIndex == -1 )
     )
  {
    //failed to create a required field
    return 8;
  }

  //progress dialog
  long featureCount = vectorProvider->featureCount();
  if ( p )
  {
    p->setMaximum( featureCount );
  }


  //iterate over each polygon
  QgsFeatureRequest request;
  request.setSubsetOfAttributes( QgsAttributeList() );
  QgsFeatureIterator fi = vectorProvider->getFeatures( request );
  QgsFeature f;

  bool statsStoreValues = ( mStatistics & QgsZonalStatistics::Median ) ||
                          ( mStatistics & QgsZonalStatistics::StDev );
  bool statsStoreValueCount = ( mStatistics & QgsZonalStatistics::Minority ) ||
                              ( mStatistics & QgsZonalStatistics::Majority );

  FeatureStats featureStats( statsStoreValues, statsStoreValueCount );
  int featureCounter = 0;

  QgsChangedAttributesMap changeMap;
  while ( fi.nextFeature( f ) )
  {
    if ( p )
    {
      p->setValue( featureCounter );
    }

    if ( p && p->wasCanceled() )
    {
      break;
    }

    if ( !f.constGeometry() )
    {
      ++featureCounter;
      continue;
    }
    const QgsGeometry* featureGeometry = f.constGeometry();

    QgsRectangle featureRect = featureGeometry->boundingBox().intersect( &rasterBBox );
    if ( featureRect.isEmpty() )
    {
      ++featureCounter;
      continue;
    }

    int offsetX, offsetY, nCellsX, nCellsY;
    if ( cellInfoForBBox( rasterBBox, featureRect, cellsizeX, cellsizeY, offsetX, offsetY, nCellsX, nCellsY ) != 0 )
    {
      ++featureCounter;
      continue;
    }

    //avoid access to cells outside of the raster (may occur because of rounding)
    if (( offsetX + nCellsX ) > nCellsXGDAL )
    {
      nCellsX = nCellsXGDAL - offsetX;
    }
    if (( offsetY + nCellsY ) > nCellsYGDAL )
    {
      nCellsY = nCellsYGDAL - offsetY;
    }

    statisticsFromMiddlePointTest( rasterBand, featureGeometry, offsetX, offsetY, nCellsX, nCellsY, cellsizeX, cellsizeY,
                                   rasterBBox, featureStats );

    if ( featureStats.count <= 1 )
    {
      //the cell resolution is probably larger than the polygon area. We switch to precise pixel - polygon intersection in this case
      statisticsFromPreciseIntersection( rasterBand, featureGeometry, offsetX, offsetY, nCellsX, nCellsY, cellsizeX, cellsizeY,
                                         rasterBBox, featureStats );
    }

    //write the statistics value to the vector data provider
    QgsAttributeMap changeAttributeMap;
    if ( mStatistics & QgsZonalStatistics::Count )
      changeAttributeMap.insert( countIndex, QVariant( featureStats.count ) );
    if ( mStatistics & QgsZonalStatistics::Sum )
      changeAttributeMap.insert( sumIndex, QVariant( featureStats.sum ) );
    if ( featureStats.count > 0 )
    {
      double mean = featureStats.sum / featureStats.count;
      if ( mStatistics & QgsZonalStatistics::Mean )
        changeAttributeMap.insert( meanIndex, QVariant( mean ) );
      if ( mStatistics & QgsZonalStatistics::Median )
      {
        qSort( featureStats.values.begin(), featureStats.values.end() );
        int size =  featureStats.values.count();
        bool even = ( size % 2 ) < 1;
        double medianValue;
        if ( even )
        {
          medianValue = ( featureStats.values.at( size / 2 - 1 ) + featureStats.values.at( size / 2 ) ) / 2;
        }
        else //odd
        {
          medianValue = featureStats.values.at(( size + 1 ) / 2 - 1 );
        }
        changeAttributeMap.insert( medianIndex, QVariant( medianValue ) );
      }
      if ( mStatistics & QgsZonalStatistics::StDev )
      {
        double sumSquared = 0;
        for ( int i = 0; i < featureStats.values.count(); ++i )
        {
          double diff = featureStats.values.at( i ) - mean;
          sumSquared += diff * diff;
        }
        double stdev = qPow( sumSquared / featureStats.values.count(), 0.5 );
        changeAttributeMap.insert( stdevIndex, QVariant( stdev ) );
      }
      if ( mStatistics & QgsZonalStatistics::Min )
        changeAttributeMap.insert( minIndex, QVariant( featureStats.min ) );
      if ( mStatistics & QgsZonalStatistics::Max )
        changeAttributeMap.insert( maxIndex, QVariant( featureStats.max ) );
      if ( mStatistics & QgsZonalStatistics::Range )
        changeAttributeMap.insert( rangeIndex, QVariant( featureStats.max - featureStats.min ) );
      if ( mStatistics & QgsZonalStatistics::Minority || mStatistics & QgsZonalStatistics::Majority )
      {
        QList<int> vals = featureStats.valueCount.values();
        qSort( vals.begin(), vals.end() );
        if ( mStatistics & QgsZonalStatistics::Minority )
        {
          float minorityKey = featureStats.valueCount.key( vals.first() );
          changeAttributeMap.insert( minorityIndex, QVariant( minorityKey ) );
        }
        if ( mStatistics & QgsZonalStatistics::Majority )
        {
          float majKey = featureStats.valueCount.key( vals.last() );
          changeAttributeMap.insert( majorityIndex, QVariant( majKey ) );
        }
      }
      if ( mStatistics & QgsZonalStatistics::Variety )
        changeAttributeMap.insert( varietyIndex, QVariant( featureStats.valueCount.count() ) );
    }

    changeMap.insert( f.id(), changeAttributeMap );
    ++featureCounter;
  }

  vectorProvider->changeAttributeValues( changeMap );

  if ( p )
  {
    p->setValue( featureCount );
  }

  GDALClose( inputDataset );
  mPolygonLayer->updateFields();

  if ( p && p->wasCanceled() )
  {
    return 9;
  }

  return 0;
}
示例#26
0
int main( int argc, char ** argv )

{
    /* Check that we are running against at least GDAL 1.4 (probably older in fact !) */
    /* Note to developers : if we use newer API, please change the requirement */
    if (atoi(GDALVersionInfo("VERSION_NUM")) < 1400)
    {
        fprintf(stderr, "At least, GDAL >= 1.4.0 is required for this version of %s, "
                "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME);
        exit(1);
    }

/* -------------------------------------------------------------------- */
/*      Generic arg processing.                                         */
/* -------------------------------------------------------------------- */
    GDALAllRegister();
    GDALSetCacheMax( 100000000 );
    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );
    
/* -------------------------------------------------------------------- */
/*      Parse arguments.                                                */
/* -------------------------------------------------------------------- */
    int i;
    const char *pszOutFile = NULL;
    const char *pszInFile = NULL;
    int nMaxNonBlack = 2;
    int nNearDist = 15;
    int bNearWhite = FALSE;
    int bSetAlpha = FALSE;
    int bSetMask = FALSE;
    const char* pszDriverName = "HFA";
    int bFormatExplicitelySet = FALSE;
    char** papszCreationOptions = NULL;
    int bQuiet = FALSE;

    Colors oColors;
    
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i], "-o") && i < argc-1 )
            pszOutFile = argv[++i];
        else if( EQUAL(argv[i], "-of") && i < argc-1 )
        {
            pszDriverName = argv[++i];
            bFormatExplicitelySet = TRUE;
        }
        else if( EQUAL(argv[i], "-white") ) {
            bNearWhite = TRUE;
        }

        /***** -color c1,c2,c3...cn *****/
        
        else if( EQUAL(argv[i], "-color") && i < argc-1 ) {
            Color oColor;
            
            /***** tokenize the arg on , *****/
            
            char **papszTokens;
            papszTokens = CSLTokenizeString2( argv[++i], ",", 0 );

            /***** loop over the tokens *****/
            
            int iToken;
            for( iToken = 0; papszTokens && papszTokens[iToken]; iToken++ )
            {

                /***** ensure the token is an int and add it to the color *****/
                
                if ( IsInt( papszTokens[iToken] ) )
                    oColor.push_back( atoi( papszTokens[iToken] ) );
                else {
                    CPLError(CE_Failure, CPLE_AppDefined,
                             "Colors must be valid integers." );
                    CSLDestroy( papszTokens );
                    exit(1);
                }
            }
            
            CSLDestroy( papszTokens );

            /***** check if the number of bands is consistant *****/

            if ( oColors.size() > 0 &&
                 oColors.front().size() != oColor.size() )
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "ERROR: all -color args must have the same number of values.\n" );
                exit(1);
            }

            /***** add the color to the colors *****/
            
            oColors.push_back( oColor );
            
        }
        
        else if( EQUAL(argv[i], "-nb") && i < argc-1 )
            nMaxNonBlack = atoi(argv[++i]);
        else if( EQUAL(argv[i], "-near") && i < argc-1 )
            nNearDist = atoi(argv[++i]);
        else if( EQUAL(argv[i], "-setalpha") )
            bSetAlpha = TRUE;
        else if( EQUAL(argv[i], "-setmask") )
            bSetMask = TRUE;
        else if( EQUAL(argv[i], "-q") || EQUAL(argv[i], "-quiet") )
            bQuiet = TRUE;
        else if( EQUAL(argv[i], "-co") && i < argc-1 )
            papszCreationOptions = CSLAddString(papszCreationOptions, argv[++i]);
        else if( argv[i][0] == '-' )
            Usage();
        else if( pszInFile == NULL )
            pszInFile = argv[i];
        else
            Usage();
    }

    if( pszInFile == NULL )
        Usage();

    if( pszOutFile == NULL )
        pszOutFile = pszInFile;

/* -------------------------------------------------------------------- */
/*      Open input file.                                                */
/* -------------------------------------------------------------------- */
    GDALDatasetH hInDS, hOutDS = NULL;
    int nXSize, nYSize, nBands;

    if( pszOutFile == pszInFile )
        hInDS = hOutDS = GDALOpen( pszInFile, GA_Update );
    else
        hInDS = GDALOpen( pszInFile, GA_ReadOnly );

    if( hInDS == NULL )
        exit( 1 );

    nXSize = GDALGetRasterXSize( hInDS );
    nYSize = GDALGetRasterYSize( hInDS );
    nBands = GDALGetRasterCount( hInDS );
    int nDstBands = nBands;

    if( hOutDS != NULL && papszCreationOptions != NULL)
    {
        CPLError(CE_Warning, CPLE_AppDefined,
                  "Warning: creation options are ignored when writing to an existing file.");
    }

/* -------------------------------------------------------------------- */
/*      Do we need to create output file?                               */
/* -------------------------------------------------------------------- */
    if( hOutDS == NULL )
    {
        GDALDriverH hDriver = GDALGetDriverByName( pszDriverName );
        if (hDriver == NULL)
            exit(1);

        if (!bQuiet && !bFormatExplicitelySet)
            CheckExtensionConsistency(pszOutFile, pszDriverName);

        if (bSetAlpha)
        {
            /***** fixme there should be a way to preserve alpha band data not in the collar *****/
            if (nBands == 4)
                nBands --;
            else
                nDstBands ++;
        }

        if (bSetMask)
        {
            if (nBands == 4)
                nDstBands = nBands = 3;
        }

        hOutDS = GDALCreate( hDriver, pszOutFile, 
                             nXSize, nYSize, nDstBands, GDT_Byte, 
                             papszCreationOptions );
        if( hOutDS == NULL )
            exit( 1 );

        double adfGeoTransform[6];

        if( GDALGetGeoTransform( hInDS, adfGeoTransform ) == CE_None )
        {
            GDALSetGeoTransform( hOutDS, adfGeoTransform );
            GDALSetProjection( hOutDS, GDALGetProjectionRef( hInDS ) );
        }
    }
    else
    {
        if (bSetAlpha)
        {
            if (nBands != 4 &&
                (nBands < 2 ||
                 GDALGetRasterColorInterpretation(GDALGetRasterBand(hOutDS, nBands)) != GCI_AlphaBand))
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                        "Last band is not an alpha band.");
                exit(1);
            }

            nBands --;
        }

        if (bSetMask)
        {
            if (nBands == 4)
                nDstBands = nBands = 3;
        }
    }

    /***** set a color if there are no colors set? *****/

    if ( oColors.size() == 0) {
        Color oColor;

        /***** loop over the bands to get the right number of values *****/

        int iBand;
        for (iBand = 0; iBand < nBands ; iBand++) {

            /***** black or white? *****/

            if (bNearWhite) 
                oColor.push_back(255);
            else
                oColor.push_back(0);
        }

        /***** add the color to the colors *****/

        oColors.push_back(oColor);
            
    }

    /***** does the number of bands match the number of color values? *****/

    if ( (int)oColors.front().size() != nBands ) {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "-color args must have the same number of values as the non alpha input band count.\n" );
        exit(1); 
    }

    /***** check the input and output datasets are the same size *****/
    
    if (GDALGetRasterXSize(hOutDS) != nXSize ||
        GDALGetRasterYSize(hOutDS) != nYSize)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "The dimensions of the output dataset don't match "
                 "the dimensions of the input dataset.");
        exit(1);
    }


    int iBand;
    for( iBand = 0; iBand < nBands; iBand++ )
    {
        GDALRasterBandH hBand = GDALGetRasterBand(hInDS, iBand+1);
        if (GDALGetRasterDataType(hBand) != GDT_Byte)
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                     "Band %d is not of type GDT_Byte. It can lead to unexpected results.", iBand+1);
        }
        if (GDALGetRasterColorTable(hBand) != NULL)
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                     "Band %d has a color table, which is ignored by nearblack. "
                     "It can lead to unexpected results.", iBand+1);
        }
    }

    GDALRasterBandH hMaskBand = NULL;
    
    if (bSetMask) {

        /***** if there isn't already a mask band on the output file create one *****/
        
        if ( GMF_PER_DATASET != GDALGetMaskFlags( GDALGetRasterBand(hOutDS, 1) ) )
        {

            if ( CE_None != GDALCreateDatasetMaskBand(hOutDS, GMF_PER_DATASET) ) {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Failed to create mask band on output DS");
                bSetMask = FALSE;
            }
        }

        if (bSetMask) {
            hMaskBand = GDALGetMaskBand(GDALGetRasterBand(hOutDS, 1));
        }
    }

/* -------------------------------------------------------------------- */
/*      Allocate a line buffer.                                         */
/* -------------------------------------------------------------------- */
    GByte *pabyLine;
    GByte *pabyMask=NULL;
    
    int   *panLastLineCounts;

    pabyLine = (GByte *) CPLMalloc(nXSize * nDstBands);
    
    if (bSetMask)
        pabyMask = (GByte *) CPLMalloc(nXSize);
    
    panLastLineCounts = (int *) CPLCalloc(sizeof(int),nXSize);

/* -------------------------------------------------------------------- */
/*      Processing data one line at a time.                             */
/* -------------------------------------------------------------------- */
    int iLine;

    for( iLine = 0; iLine < nYSize; iLine++ )
    {
        CPLErr eErr;

        eErr = GDALDatasetRasterIO( hInDS, GF_Read, 0, iLine, nXSize, 1, 
                                    pabyLine, nXSize, 1, GDT_Byte, 
                                    nBands, NULL, nDstBands, nXSize * nDstBands, 1 );
        if( eErr != CE_None )
            break;
        
        if (bSetAlpha)
        {
            int iCol;
            for(iCol = 0; iCol < nXSize; iCol ++)
            {
                pabyLine[iCol * nDstBands + nDstBands - 1] = 255;
            }
        }
        
        if (bSetMask)
        {
            int iCol;
            for(iCol = 0; iCol < nXSize; iCol ++)
            {
                pabyMask[iCol] = 255;
            }
        }
        
        ProcessLine( pabyLine, pabyMask, 0, nXSize-1, nBands, nDstBands,
                     nNearDist, nMaxNonBlack, bNearWhite, &oColors,
                     panLastLineCounts,
                     TRUE, // bDoHorizontalCheck
                     TRUE, // bDoVerticalCheck
                     FALSE // bBottomUp
                    );
        ProcessLine( pabyLine, pabyMask, nXSize-1, 0, nBands, nDstBands,
                     nNearDist, nMaxNonBlack, bNearWhite, &oColors,
                     panLastLineCounts,
                     TRUE,  // bDoHorizontalCheck
                     FALSE, // bDoVerticalCheck
                     FALSE  // bBottomUp
                    );
        
        eErr = GDALDatasetRasterIO( hOutDS, GF_Write, 0, iLine, nXSize, 1, 
                                    pabyLine, nXSize, 1, GDT_Byte, 
                                    nDstBands, NULL, nDstBands, nXSize * nDstBands, 1 );

        if( eErr != CE_None )
            break;
    
        /***** write out the mask band line *****/

        if (bSetMask) {

            eErr = GDALRasterIO ( hMaskBand, GF_Write, 0, iLine, nXSize, 1,
                                  pabyMask, nXSize, 1, GDT_Byte,
                                  0, 0 );
                             
            if( eErr != CE_None ) {
                CPLError(CE_Warning, CPLE_AppDefined,
                         "ERROR writeing out line to mask band.");
               break;
            }
        }
        
        if (!bQuiet)
            GDALTermProgress( 0.5 * ((iLine+1) / (double) nYSize), NULL, NULL );
    }

/* -------------------------------------------------------------------- */
/*      Now process from the bottom back up                            .*/
/* -------------------------------------------------------------------- */
    memset( panLastLineCounts, 0, sizeof(int) * nXSize);
    
    for( iLine = nYSize-1; iLine >= 0; iLine-- )
    {
        CPLErr eErr;

        eErr = GDALDatasetRasterIO( hOutDS, GF_Read, 0, iLine, nXSize, 1, 
                                    pabyLine, nXSize, 1, GDT_Byte, 
                                    nDstBands, NULL, nDstBands, nXSize * nDstBands, 1 );
        if( eErr != CE_None )
            break;

        /***** read the mask band line back in *****/

        if (bSetMask) {

            eErr = GDALRasterIO ( hMaskBand, GF_Read, 0, iLine, nXSize, 1,
                                  pabyMask, nXSize, 1, GDT_Byte,
                                  0, 0 );
                             
                                
            if( eErr != CE_None )
                break;
        }

        
        ProcessLine( pabyLine, pabyMask, 0, nXSize-1, nBands, nDstBands,
                     nNearDist, nMaxNonBlack, bNearWhite, &oColors,
                     panLastLineCounts,
                     TRUE, // bDoHorizontalCheck
                     TRUE, // bDoVerticalCheck
                     TRUE  // bBottomUp
                   );
        ProcessLine( pabyLine, pabyMask, nXSize-1, 0, nBands, nDstBands,
                     nNearDist, nMaxNonBlack, bNearWhite, &oColors,
                     panLastLineCounts,
                     TRUE,  // bDoHorizontalCheck
                     FALSE, // bDoVerticalCheck
                     TRUE   // bBottomUp
                    );
        
        eErr = GDALDatasetRasterIO( hOutDS, GF_Write, 0, iLine, nXSize, 1, 
                                    pabyLine, nXSize, 1, GDT_Byte, 
                                    nDstBands, NULL, nDstBands, nXSize * nDstBands, 1 );
        if( eErr != CE_None )
            break;

        /***** write out the mask band line *****/

        if (bSetMask) {

            eErr = GDALRasterIO ( hMaskBand, GF_Write, 0, iLine, nXSize, 1,
                                  pabyMask, nXSize, 1, GDT_Byte,
                                  0, 0 );
                             
                                
            if( eErr != CE_None )
                break;
        }

        
        if (!bQuiet)
            GDALTermProgress( 0.5 + 0.5 * (nYSize-iLine) / (double) nYSize, 
                            NULL, NULL );
    }

    CPLFree(pabyLine);
    if (bSetMask)
        CPLFree(pabyMask);
    
    CPLFree( panLastLineCounts );

    GDALClose( hOutDS );
    if( hInDS != hOutDS )
        GDALClose( hInDS );
    GDALDumpOpenDatasets( stderr );
    CSLDestroy( argv );
    CSLDestroy( papszCreationOptions );
    GDALDestroyDriverManager();
    
    return 0;
}
示例#27
0
SVImage init(int xLow, int xHigh, int yLow, int yHigh, const char *filepath){

    GDALDatasetH  hDataset;
    // Register drivers
    GDALAllRegister();
    
    // open the given file as Read Only
    hDataset = GDALOpen(filepath, GA_ReadOnly );
    // if opening failed
    if( hDataset == NULL )
    {
        fprintf(stderr, "Unable to open file.");
        exit(EXIT_FAILURE);
    }

    /*      Declare some variables to be used later     */
    int *xBlockSize = malloc(sizeof(int));
    int *yBlockSize = malloc(sizeof(int));
    int xOutputSize;
    int yOutputSize;
    int numXBlocks;
    int numYBlocks;
    int origWidth;
    int origHeight;
    int origBandCount;
    
    /*Get some information on the image*/
    origWidth = GDALGetRasterXSize( hDataset );                 // Get raster pixel width
    origHeight = GDALGetRasterYSize( hDataset );                // Get raster pixel height
    origBandCount = GDALGetRasterCount( hDataset );             // Get number of raster bands in the image
    GDALRasterBandH hBand = GDALGetRasterBand( hDataset, 1 );   // Get raster band with id 1
    GDALGetBlockSize( hBand, xBlockSize, yBlockSize);           // Fetch the block size for this band

    /*TODO make sure scale is set somewhere*/
    
    /*Store some information on what the output should have*/
    xOutputSize = ((*xBlockSize) / scale); // get the new x block size
    yOutputSize = ((*yBlockSize) / scale); // get the new y block size
    numXBlocks = origWidth/(*xBlockSize);  // Get x block count
    numYBlocks = origHeight/(*yBlockSize); // Get y block count

    int bandCount;
    if (origBandCount >= 3) // Just a guess, limit bands to RGB?
    {
        bandCount = 3;
    }
    else                    // Otherwise image is probably grayscale, one band?
    {
        bandCount = 1;
    }

    /*TODO edit this or remove it since we aren't using focusing on openGL*/
    /*
     *int format;
     *if (bandCount == 3)
     *{
     *    format = GL_RGBA;
     *}
     *else
     *{
     *    format = GL_LUMINANCE_ALPHA;
     *}
     */
    
    int usedBlocks;
    int usedXBlocks;
    int usedYBlocks;
    /*
     *This is odd, xHigh and yHigh are
     *passed as parameters but changed here
     *TODO see if we can remove parameters or just use this
     */

    if ((xHigh < 0) || (xHigh < xLow))
    {
        xHigh = numXBlocks;
    }
    if ((yHigh < 0)|| (yHigh < yLow))
    {
        yHigh = numYBlocks;
    }
    
    usedXBlocks = (xHigh - xLow); // This is probably the part of the image that should be displayed on screen
    usedYBlocks = (yHigh - yLow); // Y part on screen?
    usedBlocks = (usedXBlocks * usedYBlocks); // Total blocks on screen?
    
    SVImage svip = 
        {
            .Width = xOutputSize*usedXBlocks,
            .Height = yOutputSize*usedYBlocks,
            .BytesPerPixel = 1, 
            .Data = (CPLMalloc((sizeof(char) * xOutputSize * yOutputSize * usedBlocks * (bandCount+1))))
            // Data = xOutputSize * yOutputSize = pixels/block * usedBlocks = totalpixels 
        };

    free(xBlockSize);
    free(yBlockSize);
    return svip;
}


/*
Uses stochastic sampling to fill the data section of an SVImage struct.
*/
void sample(params *in)		//TODO handle 32 bit representations
{
    /*Set variables from the params struct*/
    SVImage* out = in->target;
    int xLow = in->xLow;
    int xHigh = in->xHigh;
    int yLow = in->yLow;
    int yHigh = in->yHigh;
    const char *file = in->file;

    GDALDatasetH  hDataset;
    GDALRasterBandH hBand;
    /*Register drivers*/
    GDALAllRegister();
	
    //TODO Dynamically calculate sample count?
    int avgSampleCount = 25;
 
    //Open GDAL File
    //------------------------------------------------
    hDataset = GDALOpen(file, GA_ReadOnly );
    if( hDataset == NULL )
    {
    	fprintf(stderr, "Unable to open file.\n"); 
        exit(EXIT_FAILURE);
    }
    
    //GDAL FILE INFO
    //---------------------------------------------
    GDALDriverH   hDriver;
    hDriver = GDALGetDatasetDriver( hDataset ); // Get driver for this file

    double adfGeoTransform[6];

    //Print GDAL Driver 
    printf( "Driver: %s/%s\n",
            GDALGetDriverShortName( hDriver ),
            GDALGetDriverLongName( hDriver ) );

    //Get original raster size
    int origWidth = GDALGetRasterXSize( hDataset ); 
    int origHeight = GDALGetRasterYSize( hDataset ); 
    printf("width = %i\n", origWidth);
    printf("height = %i\n", origHeight);  

    //Get Raster band count	
    int origBandCount = GDALGetRasterCount( hDataset );
    printf("origBandCount = %i\n", origBandCount);
    int bandCount;
    if (origBandCount >= 3)
    {
        bandCount = 3;
    }
    else
    {
        bandCount = 1;
    }

    //Target output Width and Height
    float stride = (scale * scale);				
    stride /= (avgSampleCount);

    //the greatest number of pixels that can be skipped in a single iteration
    int maxStride = ((int)stride) + 1;				

    //Load band 1
    hBand = GDALGetRasterBand( hDataset, 1 );

    if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None )
    {
        printf( "Pixel Size = (%.6f,%.6f)\n",
                    adfGeoTransform[1], adfGeoTransform[5] );
    }
    else
    {
        fprintf(stderr, "Failed to get pixel size\n");
    }

    int* xBlockSize = malloc(sizeof(int));
    int* yBlockSize = malloc(sizeof(int));
    //get block size
    GDALGetBlockSize( hBand, xBlockSize, yBlockSize);
    printf("xBlockSize = %i\n", *xBlockSize);
    printf("yBlockSize = %i\n", *yBlockSize);  
    int xOutputSize = ((*xBlockSize) / scale);
    int yOutputSize = ((*yBlockSize) / scale);
    printf("X Output Size%i\n", xOutputSize);
    int numXBlocks = origWidth/(*xBlockSize);
    int numYBlocks = origHeight/(*yBlockSize);
    printf("numXBlocks = %i\n", numXBlocks);
    printf("numYBlocks = %i\n", numYBlocks);
    
    if ((xHigh < 0) || (xHigh < xLow))
    {
        xHigh = numXBlocks;
    }
    if ((yHigh < 0)|| (yHigh < yLow))
    {
        yHigh = numYBlocks;
    }
    
    int usedXBlocks = (xHigh - xLow);
    int usedYBlocks = (yHigh - yLow);
    int usedBlocks = (usedXBlocks * usedYBlocks);
    
    unsigned char* output = CPLMalloc((sizeof(char) * xOutputSize* yOutputSize *usedBlocks  * (bandCount+1)));  // Allocate space for the output
    float* vals = calloc( xOutputSize* yOutputSize *usedBlocks * (bandCount+1), sizeof(float));			//stores pixel values
    unsigned long* valsPerIndex = calloc( xOutputSize* yOutputSize * usedBlocks * (bandCount+1), sizeof(unsigned long));		//stores number of pixel values per output index
    unsigned long rseed = 0;
    unsigned long rowIndex = 0;		//the index of the row to which we will output our value
    unsigned long colIndex = 0;		//the index of the column to which we will output our value
    unsigned long outIndex = 0;
    unsigned long sampledIndex = 0;	//One dimensional representation of column/row index
    
    //iterate through each pixel, jump to the last pixel we sampled.
    long long i = 0;
    int outputXOffset = 0;
    int outputYOffset = 0;
    int outputIndexOffset = 0;
    if (GDALGetRasterDataType(hBand) == GDT_Int16)
    {
        short* data = (short *) CPLMalloc(sizeof(unsigned short) * (*xBlockSize)*(*yBlockSize)); //TODO: GDAL Raster can be 16 bit pixel representation
        int band;
        for (band = 1; band <= bandCount; band++){
            hBand = GDALGetRasterBand( hDataset, band );
            int yBlock, xBlock;
            for(yBlock = yLow; yBlock < yHigh; yBlock++){
                for(xBlock = xLow; xBlock < xHigh; xBlock++){
                    if(GDALReadBlock(hBand,xBlock,yBlock, data) != CE_None)
                    {
                        fprintf(stderr, "Read block failed\n");
                        exit(EXIT_FAILURE);
                    }
                    for(i = 0 ; i < ((*xBlockSize)*(*yBlockSize)-1) ; i += rseed){
                        rseed = (214013 * rseed + 2531011); // Magic numbers.
                        rseed %= maxStride;	
                        sampledIndex = i;
                        i = (maxStride ==1) ? (i+1) : i;
                        rowIndex = (sampledIndex/(xOutputSize*scale* scale)) + ((yBlock - yLow)* yOutputSize);
                        colIndex = ((sampledIndex % (xOutputSize * scale))/scale) + ((xBlock - xLow) * xOutputSize);
                        outIndex = ((rowIndex * (xOutputSize * usedXBlocks ) + colIndex) * (bandCount+1) ) + (band -1);
                        vals[outIndex] += (*(data + sampledIndex));
                        vals[outIndex] += 118.450588 + ((*(data + sampledIndex))/128);
                        if (vals[outIndex]/valsPerIndex[outIndex] < 0) {
                            vals[outIndex] =0;
                        }else if (vals[outIndex]/valsPerIndex[outIndex] > 255){
                            vals[outIndex] = 255;
                        }
                    }
                }
            }
        }
    }
    else
    {
        unsigned char* data = (unsigned char *) CPLMalloc(sizeof(char) * (*xBlockSize)*(*yBlockSize));
        int band;
        for (band = 1; band <= bandCount; band++)
        {
            hBand = GDALGetRasterBand( hDataset, band );
            int yBlock, xBlock;
            outputYOffset = 0;
            for(yBlock = yLow; yBlock < yHigh; yBlock++){
                outputYOffset = ((yBlock - yLow) * yOutputSize * xOutputSize * usedXBlocks * (bandCount + 1));
                outputXOffset = 0;
                for(xBlock = xLow; xBlock < xHigh; xBlock++){
                    outputXOffset = ((xBlock - xLow) * xOutputSize * (bandCount + 1));
                    if(GDALReadBlock(hBand,xBlock,yBlock, data) != CE_None)
                    {
                        fprintf(stderr, "Read block failed\n");
                        exit(EXIT_FAILURE);
                    }
                    for(i = 0 ; i < ((*xBlockSize)*(*yBlockSize)) ; i += rseed){
                        rseed = (214013 * rseed + 2531011);
                        rseed %= maxStride;	
                        sampledIndex = i;
                        i = (maxStride ==1) ? (i+1) : i;
                        rowIndex = (sampledIndex/(xOutputSize*scale* scale)) + ((yBlock - yLow)* yOutputSize);
                        colIndex = ((sampledIndex % (xOutputSize * scale))/scale) + ((xBlock - xLow) * xOutputSize);
                        outIndex = ((rowIndex * (xOutputSize * usedXBlocks ) + colIndex) * (bandCount+1) ) + (band -1);
                        vals[outIndex] += (*(data + sampledIndex));
                        valsPerIndex[outIndex] +=1;
                    }
                    outputIndexOffset = (outputYOffset + outputXOffset);
                    int j;
                    for (j = 0; j<yOutputSize; j++){
                        i = outputIndexOffset;
                        int k = (i + (xOutputSize * (bandCount+1)));
                        for (i = 0; i<k;i++){
                            int x = (i+(j*(xOutputSize * (bandCount + 1) * (usedXBlocks))));
                            if(((x+1)%4==0&&bandCount==3)||((x+1)%2==0&&bandCount==1)){
                                output[x] = (unsigned char) 1; //Sets the alpha to opaque
                            }else{
                                output[x] = (unsigned char) (vals[x]/valsPerIndex[x]);	//calculate final output by averaging each color value
                            }
                        }
                    }
                    out->Data = output;
                }
            }
        }
    }

    printf("sampling complete\n");
    GDALClose(hDataset);
}
示例#28
0
int CPL_STDCALL
GDALSimpleImageWarp( GDALDatasetH hSrcDS, GDALDatasetH hDstDS,
                     int nBandCount, int *panBandList,
                     GDALTransformerFunc pfnTransform, void *pTransformArg,
                     GDALProgressFunc pfnProgress, void *pProgressArg,
                     char **papszWarpOptions )

{
    VALIDATE_POINTER1( hSrcDS, "GDALSimpleImageWarp", 0 );
    VALIDATE_POINTER1( hDstDS, "GDALSimpleImageWarp", 0 );

    bool bError = false;

/* -------------------------------------------------------------------- */
/*      If no bands provided assume we should process all bands.        */
/* -------------------------------------------------------------------- */
    if( nBandCount == 0 )
    {
        nBandCount = GDALGetRasterCount( hSrcDS );
        if (nBandCount == 0)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "No raster band in source dataset");
            return FALSE;
        }

        panBandList = (int *) CPLCalloc(sizeof(int),nBandCount);

        for( int iBand = 0; iBand < nBandCount; iBand++ )
            panBandList[iBand] = iBand+1;

        const int nResult =
            GDALSimpleImageWarp( hSrcDS, hDstDS, nBandCount, panBandList,
                                 pfnTransform, pTransformArg,
                                 pfnProgress, pProgressArg,
                                 papszWarpOptions );
        CPLFree( panBandList );
        return nResult;
    }

/* -------------------------------------------------------------------- */
/*      Post initial progress.                                          */
/* -------------------------------------------------------------------- */
    if( pfnProgress )
    {
        if( !pfnProgress( 0.0, "", pProgressArg ) )
            return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Load the source image band(s).                                  */
/* -------------------------------------------------------------------- */
    const int nSrcXSize = GDALGetRasterXSize(hSrcDS);
    const int nSrcYSize = GDALGetRasterYSize(hSrcDS);
    GByte **papabySrcData = static_cast<GByte **>(
        CPLCalloc(nBandCount, sizeof(GByte*)) );

    bool ok = true;
    for( int iBand = 0; iBand < nBandCount; iBand++ )
    {
        papabySrcData[iBand] = static_cast<GByte *>(
            VSI_MALLOC2_VERBOSE(nSrcXSize, nSrcYSize) );
        if( papabySrcData[iBand] == NULL )
        {
            CPLError( CE_Failure, CPLE_OutOfMemory,
                      "GDALSimpleImageWarp out of memory.\n" );
            ok = false;
            break;
        }

        if( GDALRasterIO( GDALGetRasterBand(hSrcDS,panBandList[iBand]), GF_Read,
                      0, 0, nSrcXSize, nSrcYSize,
                      papabySrcData[iBand], nSrcXSize, nSrcYSize, GDT_Byte,
                      0, 0 ) != CE_None )
        {
            CPLError( CE_Failure, CPLE_FileIO, "GDALSimpleImageWarp "
                      "GDALRasterIO failure %s ",
                      CPLGetLastErrorMsg() );
            ok = false;
            break;
        }
    }
    if( !ok ) {
        for( int i=0; i <= nBandCount; i++ )
        {
            VSIFree(papabySrcData[i]);
        }
        CPLFree(papabySrcData);
        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Check for remap request(s).                                     */
/* -------------------------------------------------------------------- */
    GDALSimpleWarpRemapping( nBandCount, papabySrcData, nSrcXSize, nSrcYSize,
                             papszWarpOptions );

/* -------------------------------------------------------------------- */
/*      Allocate scanline buffers for output image.                     */
/* -------------------------------------------------------------------- */
    const int nDstXSize = GDALGetRasterXSize( hDstDS );
    const int nDstYSize = GDALGetRasterYSize( hDstDS );
    GByte **papabyDstLine = static_cast<GByte **>(
        CPLCalloc(nBandCount, sizeof(GByte*)) );

    for( int iBand = 0; iBand < nBandCount; iBand++ )
        papabyDstLine[iBand] = static_cast<GByte *>(CPLMalloc( nDstXSize ));

/* -------------------------------------------------------------------- */
/*      Allocate x,y,z coordinate arrays for transformation ... one     */
/*      scanlines worth of positions.                                   */
/* -------------------------------------------------------------------- */
    double *padfX = static_cast<double *>(
        CPLMalloc(sizeof(double) * nDstXSize) );
    double *padfY = static_cast<double *>(
        CPLMalloc(sizeof(double) * nDstXSize) );
    double *padfZ = static_cast<double *>(
        CPLMalloc(sizeof(double) * nDstXSize) );
    int *pabSuccess = static_cast<int *>( CPLMalloc(sizeof(int) * nDstXSize) );

/* -------------------------------------------------------------------- */
/*      Establish the value we will use to initialize the bands.  We    */
/*      default to -1 indicating the initial value should be read       */
/*      and preserved from the source file, but allow this to be        */
/*      overridden by passed                                            */
/*      option(s).                                                      */
/* -------------------------------------------------------------------- */
    int * const panBandInit =
        static_cast<int *>( CPLCalloc(sizeof(int), nBandCount) );
    if( CSLFetchNameValue( papszWarpOptions, "INIT" ) )
    {
        char **papszTokens =
            CSLTokenizeStringComplex( CSLFetchNameValue( papszWarpOptions,
                                                         "INIT" ),
                                      " ,", FALSE, FALSE );

        const int nTokenCount = CSLCount(papszTokens);

        for( int iBand = 0; iBand < nBandCount; iBand++ )
        {
            if( nTokenCount == 0 )
                panBandInit[iBand] = 0;
            else
                panBandInit[iBand] =
                    atoi(papszTokens[MIN(iBand,nTokenCount-1)]);
        }

        CSLDestroy(papszTokens);
    }

/* -------------------------------------------------------------------- */
/*      Loop over all the scanlines in the output image.                */
/* -------------------------------------------------------------------- */
    for( int iDstY = 0; iDstY < nDstYSize; iDstY++ )
    {
        // Clear output buffer to "transparent" value.  Should not we
        // really be reading from the destination file to support overlay?
        for( int iBand = 0; iBand < nBandCount; iBand++ )
        {
            if( panBandInit[iBand] == -1 )
            {
                if( GDALRasterIO( GDALGetRasterBand(hDstDS,iBand+1), GF_Read,
                              0, iDstY, nDstXSize, 1,
                              papabyDstLine[iBand], nDstXSize, 1, GDT_Byte,
                              0, 0 ) != CE_None )
                {
                    bError = TRUE;
                    break;
                }
            }
            else
                memset( papabyDstLine[iBand], panBandInit[iBand], nDstXSize );
        }

        // Set point to transform.
        for( int iDstX = 0; iDstX < nDstXSize; iDstX++ )
        {
            padfX[iDstX] = iDstX + 0.5;
            padfY[iDstX] = iDstY + 0.5;
            padfZ[iDstX] = 0.0;
        }

        // Transform the points from destination pixel/line coordinates
        // to source pixel/line coordinates.
        pfnTransform( pTransformArg, TRUE, nDstXSize,
                      padfX, padfY, padfZ, pabSuccess );

        // Loop over the output scanline.
        for( int iDstX = 0; iDstX < nDstXSize; iDstX++ )
        {
            if( !pabSuccess[iDstX] )
                continue;

            // We test against the value before casting to avoid the
            // problem of asymmetric truncation effects around zero.  That is
            // -0.5 will be 0 when cast to an int.
            if( padfX[iDstX] < 0.0 || padfY[iDstX] < 0.0 )
                continue;

            const int iSrcX = static_cast<int>( padfX[iDstX] );
            const int iSrcY = static_cast<int>( padfY[iDstX] );

            if( iSrcX >= nSrcXSize || iSrcY >= nSrcYSize )
                continue;

            const int iSrcOffset = iSrcX + iSrcY * nSrcXSize;

            for( int iBand = 0; iBand < nBandCount; iBand++ )
                papabyDstLine[iBand][iDstX] = papabySrcData[iBand][iSrcOffset];
        }

        // Write scanline to disk.
        for( int iBand = 0; iBand < nBandCount; iBand++ )
        {
            if( GDALRasterIO( GDALGetRasterBand(hDstDS,iBand+1), GF_Write,
                          0, iDstY, nDstXSize, 1,
                          papabyDstLine[iBand], nDstXSize, 1, GDT_Byte, 0, 0 ) != CE_None )
            {
                bError = TRUE;
                break;
            }
        }

        if( pfnProgress != NULL )
        {
            if( !pfnProgress( (iDstY+1) / (double) nDstYSize,
                              "", pProgressArg ) )
            {
                CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" );
                bError = TRUE;
                break;
            }
        }
    }

/* -------------------------------------------------------------------- */
/*      Cleanup working buffers.                                        */
/* -------------------------------------------------------------------- */
    for( int iBand = 0; iBand < nBandCount; iBand++ )
    {
        CPLFree( papabyDstLine[iBand] );
        CPLFree( papabySrcData[iBand] );
    }

    CPLFree( panBandInit );
    CPLFree( papabyDstLine );
    CPLFree( papabySrcData );
    CPLFree( padfX );
    CPLFree( padfY );
    CPLFree( padfZ );
    CPLFree( pabSuccess );

    return !bError;
}
示例#29
0
GDALDatasetH CPL_STDCALL 
GDALAutoCreateWarpedVRT( GDALDatasetH hSrcDS, 
                         const char *pszSrcWKT,
                         const char *pszDstWKT,
                         GDALResampleAlg eResampleAlg, 
                         double dfMaxError, 
                         const GDALWarpOptions *psOptionsIn )
    
{
    GDALWarpOptions *psWO;
    int i;

    VALIDATE_POINTER1( hSrcDS, "GDALAutoCreateWarpedVRT", NULL );

/* -------------------------------------------------------------------- */
/*      Populate the warp options.                                      */
/* -------------------------------------------------------------------- */
    if( psOptionsIn != NULL )
        psWO = GDALCloneWarpOptions( psOptionsIn );
    else
        psWO = GDALCreateWarpOptions();

    psWO->eResampleAlg = eResampleAlg;

    psWO->hSrcDS = hSrcDS;

    psWO->nBandCount = GDALGetRasterCount( hSrcDS );
    psWO->panSrcBands = (int *) CPLMalloc(sizeof(int) * psWO->nBandCount);
    psWO->panDstBands = (int *) CPLMalloc(sizeof(int) * psWO->nBandCount);

    for( i = 0; i < psWO->nBandCount; i++ )
    {
        psWO->panSrcBands[i] = i+1;
        psWO->panDstBands[i] = i+1;
    }

    /* TODO: should fill in no data where available */

/* -------------------------------------------------------------------- */
/*      Create the transformer.                                         */
/* -------------------------------------------------------------------- */
    psWO->pfnTransformer = GDALGenImgProjTransform;
    psWO->pTransformerArg = 
        GDALCreateGenImgProjTransformer( psWO->hSrcDS, pszSrcWKT, 
                                         NULL, pszDstWKT,
                                         TRUE, 1.0, 0 );

    if( psWO->pTransformerArg == NULL )
    {
        GDALDestroyWarpOptions( psWO );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Figure out the desired output bounds and resolution.            */
/* -------------------------------------------------------------------- */
    double adfDstGeoTransform[6];
    int    nDstPixels, nDstLines;
    CPLErr eErr;

    eErr = 
        GDALSuggestedWarpOutput( hSrcDS, psWO->pfnTransformer, 
                                 psWO->pTransformerArg, 
                                 adfDstGeoTransform, &nDstPixels, &nDstLines );

/* -------------------------------------------------------------------- */
/*      Update the transformer to include an output geotransform        */
/*      back to pixel/line coordinates.                                 */
/*                                                                      */
/* -------------------------------------------------------------------- */
    GDALSetGenImgProjTransformerDstGeoTransform( 
        psWO->pTransformerArg, adfDstGeoTransform );

/* -------------------------------------------------------------------- */
/*      Do we want to apply an approximating transformation?            */
/* -------------------------------------------------------------------- */
    if( dfMaxError > 0.0 )
    {
        psWO->pTransformerArg = 
            GDALCreateApproxTransformer( psWO->pfnTransformer, 
                                         psWO->pTransformerArg, 
                                         dfMaxError );
        psWO->pfnTransformer = GDALApproxTransform;
    }

/* -------------------------------------------------------------------- */
/*      Create the VRT file.                                            */
/* -------------------------------------------------------------------- */
    GDALDatasetH hDstDS;

    hDstDS = GDALCreateWarpedVRT( hSrcDS, nDstPixels, nDstLines, 
                                  adfDstGeoTransform, psWO );

    GDALDestroyWarpOptions( psWO );

    if( pszDstWKT != NULL )
        GDALSetProjection( hDstDS, pszDstWKT );
    else if( pszSrcWKT != NULL )
        GDALSetProjection( hDstDS, pszDstWKT );
    else if( GDALGetGCPCount( hSrcDS ) > 0 )
        GDALSetProjection( hDstDS, GDALGetGCPProjection( hSrcDS ) );
    else 
        GDALSetProjection( hDstDS, GDALGetProjectionRef( hSrcDS ) );

    return hDstDS;
}
示例#30
-1
int main( int argc, char ** argv )

{
    GDALDatasetH	hSrcDS, hDstDS;
    GDALDataset *       poSrcDS, *poDstDS = NULL;
    int			i;
    int			nRasterXSize, nRasterYSize;
    const char		*pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff";
    GDALDriverH		hDriver;
    int			*panBandList = NULL, nBandCount = 0, bDefBands = TRUE;
    GDALDataType	eOutputType = GDT_Unknown;
    int			nOXSize = 0, nOYSize = 0;
    char                **papszCreateOptions = NULL;
    char                **papszAsyncOptions = NULL;
    int                 anSrcWin[4];
    int                 bQuiet = FALSE;
    GDALProgressFunc    pfnProgress = GDALTermProgress;
    int                 iSrcFileArg = -1, iDstFileArg = -1;
    int                 bMulti = FALSE;
    double              dfTimeout = -1.0;
    const char          *pszOXSize = NULL, *pszOYSize = NULL;

    anSrcWin[0] = 0;
    anSrcWin[1] = 0;
    anSrcWin[2] = 0;
    anSrcWin[3] = 0;

    /* Check strict compilation and runtime library version as we use C++ API */
    if (! GDAL_CHECK_VERSION(argv[0]))
        exit(1);

    /* -------------------------------------------------------------------- */
    /*      Register standard GDAL drivers, and process generic GDAL        */
    /*      command options.                                                */
    /* -------------------------------------------------------------------- */
    GDALAllRegister();
    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );

    /* -------------------------------------------------------------------- */
    /*      Handle command line arguments.                                  */
    /* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i],"-of") && i < argc-1 )
            pszFormat = argv[++i];

        else if( EQUAL(argv[i],"-quiet") )
        {
            bQuiet = TRUE;
            pfnProgress = GDALDummyProgress;
        }

        else if( EQUAL(argv[i],"-ot") && i < argc-1 )
        {
            int	iType;

            for( iType = 1; iType < GDT_TypeCount; iType++ )
            {
                if( GDALGetDataTypeName((GDALDataType)iType) != NULL
                        && EQUAL(GDALGetDataTypeName((GDALDataType)iType),
                                 argv[i+1]) )
                {
                    eOutputType = (GDALDataType) iType;
                }
            }

            if( eOutputType == GDT_Unknown )
            {
                printf( "Unknown output pixel type: %s\n", argv[i+1] );
                Usage();
                GDALDestroyDriverManager();
                exit( 2 );
            }
            i++;
        }

        else if( EQUAL(argv[i],"-b") && i < argc-1 )
        {
            if( atoi(argv[i+1]) < 1 )
            {
                printf( "Unrecognizable band number (%s).\n", argv[i+1] );
                Usage();
                GDALDestroyDriverManager();
                exit( 2 );
            }

            nBandCount++;
            panBandList = (int *)
                          CPLRealloc(panBandList, sizeof(int) * nBandCount);
            panBandList[nBandCount-1] = atoi(argv[++i]);

            if( panBandList[nBandCount-1] != nBandCount )
                bDefBands = FALSE;
        }
        else if( EQUAL(argv[i],"-co") && i < argc-1 )
        {
            papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] );
        }

        else if( EQUAL(argv[i],"-ao") && i < argc-1 )
        {
            papszAsyncOptions = CSLAddString( papszAsyncOptions, argv[++i] );
        }

        else if( EQUAL(argv[i],"-to") && i < argc-1 )
        {
            dfTimeout = atof(argv[++i] );
        }

        else if( EQUAL(argv[i],"-outsize") && i < argc-2 )
        {
            pszOXSize = argv[++i];
            pszOYSize = argv[++i];
        }

        else if( EQUAL(argv[i],"-srcwin") && i < argc-4 )
        {
            anSrcWin[0] = atoi(argv[++i]);
            anSrcWin[1] = atoi(argv[++i]);
            anSrcWin[2] = atoi(argv[++i]);
            anSrcWin[3] = atoi(argv[++i]);
        }

        else if( EQUAL(argv[i],"-multi") )
        {
            bMulti = TRUE;
        }
        else if( argv[i][0] == '-' )
        {
            printf( "Option %s incomplete, or not recognised.\n\n",
                    argv[i] );
            Usage();
            GDALDestroyDriverManager();
            exit( 2 );
        }
        else if( pszSource == NULL )
        {
            iSrcFileArg = i;
            pszSource = argv[i];
        }
        else if( pszDest == NULL )
        {
            pszDest = argv[i];
            iDstFileArg = i;
        }

        else
        {
            printf( "Too many command options.\n\n" );
            Usage();
            GDALDestroyDriverManager();
            exit( 2 );
        }
    }

    if( pszDest == NULL )
    {
        Usage();
        GDALDestroyDriverManager();
        exit( 10 );
    }

    if ( strcmp(pszSource, pszDest) == 0)
    {
        fprintf(stderr, "Source and destination datasets must be different.\n");
        GDALDestroyDriverManager();
        exit( 1 );
    }

    /* -------------------------------------------------------------------- */
    /*      Attempt to open source file.                                    */
    /* -------------------------------------------------------------------- */

    hSrcDS = GDALOpenShared( pszSource, GA_ReadOnly );
    poSrcDS = (GDALDataset *) hSrcDS;

    if( hSrcDS == NULL )
    {
        fprintf( stderr,
                 "GDALOpen failed - %d\n%s\n",
                 CPLGetLastErrorNo(), CPLGetLastErrorMsg() );
        GDALDestroyDriverManager();
        exit( 1 );
    }

    /* -------------------------------------------------------------------- */
    /*      Collect some information from the source file.                  */
    /* -------------------------------------------------------------------- */
    nRasterXSize = GDALGetRasterXSize( hSrcDS );
    nRasterYSize = GDALGetRasterYSize( hSrcDS );

    if( !bQuiet )
        printf( "Input file size is %d, %d\n", nRasterXSize, nRasterYSize );

    if( anSrcWin[2] == 0 && anSrcWin[3] == 0 )
    {
        anSrcWin[2] = nRasterXSize;
        anSrcWin[3] = nRasterYSize;
    }

    /* -------------------------------------------------------------------- */
    /*      Establish output size.                                          */
    /* -------------------------------------------------------------------- */
    if( pszOXSize == NULL )
    {
        nOXSize = anSrcWin[2];
        nOYSize = anSrcWin[3];
    }
    else
    {
        nOXSize = (int) ((pszOXSize[strlen(pszOXSize)-1]=='%'
                          ? atof(pszOXSize)/100*anSrcWin[2] : atoi(pszOXSize)));
        nOYSize = (int) ((pszOYSize[strlen(pszOYSize)-1]=='%'
                          ? atof(pszOYSize)/100*anSrcWin[3] : atoi(pszOYSize)));
    }

    /* -------------------------------------------------------------------- */
    /*	Build band list to translate					*/
    /* -------------------------------------------------------------------- */
    if( nBandCount == 0 )
    {
        nBandCount = GDALGetRasterCount( hSrcDS );
        if( nBandCount == 0 )
        {
            fprintf( stderr, "Input file has no bands, and so cannot be translated.\n" );
            GDALDestroyDriverManager();
            exit(1 );
        }

        panBandList = (int *) CPLMalloc(sizeof(int)*nBandCount);
        for( i = 0; i < nBandCount; i++ )
            panBandList[i] = i+1;
    }
    else
    {
        for( i = 0; i < nBandCount; i++ )
        {
            if( panBandList[i] < 1 || panBandList[i] > GDALGetRasterCount(hSrcDS) )
            {
                fprintf( stderr,
                         "Band %d requested, but only bands 1 to %d available.\n",
                         panBandList[i], GDALGetRasterCount(hSrcDS) );
                GDALDestroyDriverManager();
                exit( 2 );
            }
        }

        if( nBandCount != GDALGetRasterCount( hSrcDS ) )
            bDefBands = FALSE;
    }

    /* -------------------------------------------------------------------- */
    /*      Verify source window.                                           */
    /* -------------------------------------------------------------------- */
    if( anSrcWin[0] < 0 || anSrcWin[1] < 0
            || anSrcWin[2] <= 0 || anSrcWin[3] <= 0
            || anSrcWin[0] + anSrcWin[2] > GDALGetRasterXSize(hSrcDS)
            || anSrcWin[1] + anSrcWin[3] > GDALGetRasterYSize(hSrcDS) )
    {
        fprintf( stderr,
                 "-srcwin %d %d %d %d falls outside raster size of %dx%d\n"
                 "or is otherwise illegal.\n",
                 anSrcWin[0],
                 anSrcWin[1],
                 anSrcWin[2],
                 anSrcWin[3],
                 GDALGetRasterXSize(hSrcDS),
                 GDALGetRasterYSize(hSrcDS) );
        exit( 1 );
    }

    /* -------------------------------------------------------------------- */
    /*      Find the output driver.                                         */
    /* -------------------------------------------------------------------- */
    hDriver = GDALGetDriverByName( pszFormat );

    if( hDriver == NULL )
    {
        printf( "Output driver `%s' not recognised.\n", pszFormat );
    }
    else if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) == NULL )
    {
        printf( "Output driver '%s' does not support direct creation.\n",
                pszFormat );
        hDriver = NULL;
    }

    if( hDriver == NULL )
    {
        int	iDr;

        printf( "The following format drivers are configured and support output:\n" );
        for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ )
        {
            GDALDriverH hDriver = GDALGetDriver(iDr);

            if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) != NULL )
            {
                printf( "  %s: %s\n",
                        GDALGetDriverShortName( hDriver  ),
                        GDALGetDriverLongName( hDriver ) );
            }
        }
        printf( "\n" );
        Usage();

        GDALClose( hSrcDS );
        CPLFree( panBandList );
        GDALDestroyDriverManager();
        CSLDestroy( argv );
        CSLDestroy( papszCreateOptions );
        exit( 1 );
    }

    /* -------------------------------------------------------------------- */
    /*      Establish the pixel data type to use.                           */
    /* -------------------------------------------------------------------- */
    if( eOutputType == GDT_Unknown )
        eOutputType = poSrcDS->GetRasterBand(1)->GetRasterDataType();

    /* -------------------------------------------------------------------- */
    /*      Allocate one big buffer for the whole imagery area to           */
    /*      transfer.                                                       */
    /* -------------------------------------------------------------------- */
    int nBytesPerPixel = nBandCount * (GDALGetDataTypeSize(eOutputType) / 8);
    void *pImage = VSIMalloc3( nOXSize, nOYSize, nBytesPerPixel );

    if( pImage == NULL )
    {
        printf( "Unable to allocate %dx%dx%d byte window buffer.\n",
                nOXSize, nOYSize, nBytesPerPixel );
        exit( 1 );
    }

    /* -------------------------------------------------------------------- */
    /*      Establish view window                                           */
    /* -------------------------------------------------------------------- */
    GDALAsyncReader *poAsyncReq;
    int nPixelSpace = nBytesPerPixel;
    int nLineSpace = nBytesPerPixel * nOXSize;
    int nBandSpace = nBytesPerPixel / nBandCount;

    poAsyncReq = poSrcDS->BeginAsyncReader(
                     anSrcWin[0], anSrcWin[1], anSrcWin[2], anSrcWin[3],
                     pImage, nOXSize, nOYSize, eOutputType,
                     nBandCount, panBandList,
                     nPixelSpace, nLineSpace, nBandSpace, papszAsyncOptions );

    if( poAsyncReq == NULL )
        exit( 1 );

    /* -------------------------------------------------------------------- */
    /*      Process until done or an error.                                 */
    /* -------------------------------------------------------------------- */
    GDALAsyncStatusType eAStatus;
    CPLErr eErr = CE_None;
    int iMultiCounter = 0;

    hDstDS = NULL;

    do
    {
        /* ==================================================================== */
        /*      Create the output file, and initialize if needed.               */
        /* ==================================================================== */
        if( hDstDS == NULL )
        {
            CPLString osOutFilename = pszDest;

            if( bMulti )
                osOutFilename.Printf( "%s_%d", pszDest, iMultiCounter++ );

            hDstDS = GDALCreate( hDriver, osOutFilename, nOXSize, nOYSize,
                                 nBandCount, eOutputType,
                                 papszCreateOptions );
            if (hDstDS == NULL)
            {
                exit(1);
            }

            poDstDS = (GDALDataset *) hDstDS;

            /* -------------------------------------------------------------------- */
            /*      Copy georeferencing.                                            */
            /* -------------------------------------------------------------------- */
            double adfGeoTransform[6];

            if( poSrcDS->GetGeoTransform( adfGeoTransform ) == CE_None )
            {
                adfGeoTransform[0] += anSrcWin[0] * adfGeoTransform[1]
                                      + anSrcWin[1] * adfGeoTransform[2];
                adfGeoTransform[3] += anSrcWin[0] * adfGeoTransform[4]
                                      + anSrcWin[1] * adfGeoTransform[5];

                adfGeoTransform[1] *= anSrcWin[2] / (double) nOXSize;
                adfGeoTransform[2] *= anSrcWin[3] / (double) nOYSize;
                adfGeoTransform[4] *= anSrcWin[2] / (double) nOXSize;
                adfGeoTransform[5] *= anSrcWin[3] / (double) nOYSize;

                poDstDS->SetGeoTransform( adfGeoTransform );
            }

            poDstDS->SetProjection( poSrcDS->GetProjectionRef() );

            /* -------------------------------------------------------------------- */
            /*      Transfer generally applicable metadata.                         */
            /* -------------------------------------------------------------------- */
            poDstDS->SetMetadata( poSrcDS->GetMetadata() );
        }

        /* ==================================================================== */
        /*      Fetch an update and write it to the output file.                */
        /* ==================================================================== */


        int nUpXOff, nUpYOff, nUpXSize, nUpYSize;

        eAStatus = poAsyncReq->GetNextUpdatedRegion( dfTimeout,
                   &nUpXOff, &nUpYOff,
                   &nUpXSize, &nUpYSize );

        if( eAStatus != GARIO_UPDATE && eAStatus != GARIO_COMPLETE )
            continue;

        if( !bQuiet )
        {
            printf( "Got %dx%d @ (%d,%d)\n",
                    nUpXSize, nUpYSize, nUpXOff, nUpYOff );
        }

        poAsyncReq->LockBuffer();
        eErr =
            poDstDS->RasterIO( GF_Write, nUpXOff, nUpYOff, nUpXSize, nUpYSize,
                               ((GByte *) pImage)
                               + nUpXOff * nPixelSpace
                               + nUpYOff * nLineSpace,
                               nUpXSize, nUpYSize, eOutputType,
                               nBandCount, NULL,
                               nPixelSpace, nLineSpace, nBandSpace );
        poAsyncReq->UnlockBuffer();

        /* -------------------------------------------------------------------- */
        /*      In multi mode we will close this file and reopen another for    */
        /*      the next request.                                               */
        /* -------------------------------------------------------------------- */
        if( bMulti )
        {
            GDALClose( hDstDS );
            hDstDS = NULL;
        }
        else
            GDALFlushCache( hDstDS );

    } while( eAStatus != GARIO_ERROR && eAStatus != GARIO_COMPLETE
             && eErr == CE_None );

    poSrcDS->EndAsyncReader( poAsyncReq );

    /* -------------------------------------------------------------------- */
    /*      Cleanup.                                                        */
    /* -------------------------------------------------------------------- */
    VSIFree( pImage );

    if( hDstDS )
        GDALClose( hDstDS );

    GDALClose( hSrcDS );

    CPLFree( panBandList );

    CSLDestroy( argv );
    CSLDestroy( papszCreateOptions );
    CSLDestroy( papszAsyncOptions );

    GDALDumpOpenDatasets( stderr );
    GDALDestroyDriverManager();
}