예제 #1
0
def calculate_mean_of_images(images_list):
    if len(images_list)<1:
        basic.outputlogMessage('No image in the list')
        return False
    # get band number
    img_obj = RSImageclass()
    first_img = get_first_path_in_line(images_list[0])
    if first_img is False:
        return False
    img_obj.open(first_img)
    band_count = img_obj.GetBandCount()
    img_obj = None

    mean_of_images = []  # each band has one value
    for i in range(0,band_count):
        mean_of_images.append(0.0)
    total_pixel = 0

    number = 0
    for image in images_list:
        (width,height,mean_of_band) = cal_the_mean_of_bands(image)
        pixel_count = width*height
        number = number +1
        print ('%d / %d'%(number,len(images_list)))
        if width is False:
            return False
        if len(mean_of_band) != band_count:
            basic.outputlogMessage('error, band count is different')
            return False
        for i in range(0, band_count):
            mean_of_images[i] = (mean_of_images[i]*total_pixel + mean_of_band[i]*pixel_count)

        total_pixel = total_pixel + width*height
        for i in range(0, band_count):
            mean_of_images[i] = mean_of_images[i]/total_pixel


    for i in range(0, band_count):
        basic.outputlogMessage('band {}: mean {}'.format(i+1, mean_of_images[i]))

    f_obj =  open('mean_value.txt','w')
    f_obj.writelines('total image count {} \n'.format(len(images_list)))
    for i in range(0,len(mean_of_images)):
        f_obj.writelines('band {} \n'.format(i + 1))
    for i in range(0,len(mean_of_images)):
        f_obj.writelines('mean_value: {} \n'.format(mean_of_images[i]))
    f_obj.close()

    return mean_of_images
예제 #2
0
def calculate_mean_of_images(images_list):
    if len(images_list)<1:
        basic.outputlogMessage('No image in the list')
        return False
    # get band number
    img_obj = RSImageclass()
    img_obj.open(images_list[0])
    band_count = img_obj.GetBandCount()
    img_obj = None

    mean_of_images = []  # each band has one value
    for i in range(0,band_count):
        mean_of_images.append(0.0)
    total_pixel = 0

    number = 0
    for image in images_list:
        (width,height,mean_of_band) = cal_the_mean_of_bands(image)
        pixel_count = width*height
        number = number +1
        print ('%d / %d'%(number,len(images_list)))
        if width is False:
            return False
        if len(mean_of_band) != band_count:
            basic.outputlogMessage('error, band count is different')
            return False
        for i in range(0, band_count):
            mean_of_images[i] = (mean_of_images[i]*total_pixel + mean_of_band[i]*pixel_count)

        total_pixel = total_pixel + width*height
        for i in range(0, band_count):
            mean_of_images[i] = mean_of_images[i]/total_pixel


    for i in range(0, band_count):
        basic.outputlogMessage('band {}: mean {}'.format(i+1,mean_of_images[i]))
    return mean_of_images
예제 #3
0
    def compose_two_image(self, main_image, second_image, nodata):

        if io_function.is_file_exist(main_image) is False:
            return False
        if io_function.is_file_exist(second_image) is False:
            return False
        main_img = RSImageclass()
        if main_img.open(main_image) is False:
            return False
        width_main = main_img.GetWidth()
        height_main = main_img.GetHeight()
        bandcount_main = main_img.GetBandCount()

        sec_img = RSImageclass()
        if sec_img.open(second_image) is False:
            return False
        width_sec = sec_img.GetWidth()
        height_sec = sec_img.GetHeight()
        bandcount_sec = sec_img.GetBandCount()

        if width_main != width_sec or height_main != height_sec or bandcount_main != bandcount_sec:
            basic.outputlogMessage(
                'Error: The dimension of two composed images is different')
            return False
        if main_img.GetGDALDataType() != sec_img.GetGDALDataType(
        ) or main_img.GetGDALDataType() != 6:
            basic.outputlogMessage(
                'Error: The Data type of two composed imagaes is different or is not float'
            )
            return False

        outputfile = io_function.get_name_by_adding_tail(main_image, 'comp')
        imagenew = RSImageclass()
        width = width_main
        height = height_main
        if not imagenew.New(outputfile, width, height, bandcount_main,
                            main_img.GetGDALDataType()):
            return False
        for i in range(0, bandcount_main):
            bandindex = i + 1
            band_main_str = main_img.ReadbandData(bandindex, 0, 0, width,
                                                  height,
                                                  main_img.GetGDALDataType())
            band_sec_str = sec_img.ReadbandData(bandindex, 0, 0, width, height,
                                                sec_img.GetGDALDataType())

            band_main_data = struct.unpack('f' * width * height, band_main_str)
            band_main_numpy = numpy.asarray(band_main_data)

            band_sec_data = struct.unpack('f' * width * height, band_sec_str)
            band_sec_numpy = numpy.asarray(band_sec_data)

            compose_loc = numpy.where(
                (numpy.fabs(band_main_numpy - nodata) < 0.0001)
                & (numpy.fabs(band_sec_numpy - nodata) > 0.0001))
            band_main_numpy[compose_loc] = band_sec_numpy[compose_loc]
            basic.outputlogMessage('outputfortest2: compose_loc_num = %d' %
                                   numpy.array(compose_loc).size)

            templist = band_main_numpy.tolist()
            band_composed_str = struct.pack('%sf' % width * height, *templist)
            if imagenew.WritebandData(bandindex, 0, 0, width, height,
                                      band_composed_str,
                                      imagenew.GetGDALDataType()) is False:
                return False
            imagenew.SetBandNoDataValue(bandindex, nodata)

        imagenew.SetGeoTransform(main_img.GetGeoTransform())
        imagenew.SetProjection(main_img.GetProjection())

        main_img = None
        sec_img = None
        imagenew = None

        return outputfile
예제 #4
0
def setGCPsfromptsFile(imagefile, projection, GeoTransform, ptsfile):
    if not is_file_exist(imagefile):
        return False
    image = RSImageclass()
    if not image.open(imagefile):
        return False
    ngcpcount = image.ds.GetGCPCount()
    if ngcpcount > 0:
        basic.outputlogMessage(
            'warning: The file already have GCP,GCP count is ' +
            str(ngcpcount))

    allgcps = []
    inputfile_object = open(ptsfile, 'r')
    all_points = inputfile_object.readlines()
    for linestr in all_points:
        if linestr[0:1] == '#' or linestr[0:1] == ';' or len(linestr) < 2:
            continue
        if len(allgcps) >= 10000:
            basic.outputlogMessage(
                'warning: the count of gcps already greater than 10000, and ignore the others to make geotiff work correctly'
            )
            continue
        tiepointXY = linestr.split()
        base_x = float(tiepointXY[0])
        base_y = float(tiepointXY[1])
        Xp = GeoTransform[
            0] + base_x * GeoTransform[1] + base_y * GeoTransform[2]
        Yp = GeoTransform[
            3] + base_x * GeoTransform[4] + base_y * GeoTransform[5]

        warp_x = float(tiepointXY[2])
        warp_y = float(tiepointXY[3])
        info = 'GCPbysiftgpu_%d' % len(allgcps)
        id = str(len(allgcps))
        gcp1 = gdal.GCP(Xp, Yp, 0, warp_x, warp_y, info, id)
        allgcps.append(gcp1)
    inputfile_object.close()

    Outputtiff = imagefile.split('.')[0] + '_new.tif'
    format = "GTiff"
    driver = gdal.GetDriverByName(format)
    metadata = driver.GetMetadata()
    if metadata.has_key(
            gdal.DCAP_CREATE) and metadata[gdal.DCAP_CREATE] == 'YES':
        basic.outputlogMessage('Driver %s supports Create() method.' % format)
    else:
        basic.outputlogMessage('Driver %s not supports Create() method.' %
                               format)
        return False
    # if metadata.has_key(gdal.DCAP_CREATECOPY) and metadata[gdal.DCAP_CREATECOPY] == 'YES':
    #     syslog.outputlogMessage('Driver %s supports CreateCopy() method.' % format)

    # dst_ds = driver.CreateCopy(Outputtiff, dataset, 0)
    datatype = image.GetGDALDataType()
    dst_ds = driver.Create(Outputtiff, image.GetWidth(), image.GetHeight(),
                           image.GetBandCount(), datatype)
    for bandindex in range(0, image.GetBandCount()):
        bandobject = image.Getband(bandindex + 1)
        banddata = bandobject.ReadRaster(0, 0, image.GetWidth(),
                                         image.GetHeight(), image.GetWidth(),
                                         image.GetHeight(), datatype)
        #byte
        # if banddata is 1:
        #     bandarray = struct.unpack('B'*image.GetWidth()*image.GetHeight(), banddata)
        dst_ds.GetRasterBand(bandindex + 1).WriteRaster(
            0, 0, image.GetWidth(), image.GetHeight(), banddata,
            image.GetWidth(), image.GetHeight(), datatype)

    dst_ds.SetGCPs(allgcps, projection)

    # if I have set the GCPs, should not do this again, or SetGCPs will be undo
    # dst_ds.SetGeoTransform(image.GetGeoTransform())
    # dst_ds.SetProjection(image.GetProjection())

    if not os.path.isfile(Outputtiff):
        basic.outputlogMessage(
            'result file not exist, the operation of create set gcp failed')
        return False
    dst_ds = None
    image = None

    return Outputtiff
예제 #5
0
class RSImgProclass(object):
    def __init__(self):
        self.imgpath = ''
        self.img__obj = None    #RSImageclass  object

    def __del__(self):
        # close dataset
        # print 'RSImageclass__del__'
        self.img__obj = None

    def Read_Image_band_data_to_numpy_array_all_pixel(self,bandindex,image_path):
        if io_function.is_file_exist(image_path) is False:
            return False
        self.img__obj =  RSImageclass()
        if self.img__obj.open(image_path) is False:
            return False
        width = self.img__obj.GetWidth()
        height = self.img__obj.GetHeight()
        return self.__Read_band_data_to_numpy_array(bandindex,0,0,width,height,self.img__obj)

    def Read_Image_data_to_numpy_array_all_band_pixel(self,image_path):
        if io_function.is_file_exist(image_path) is False:
            return False
        self.img__obj =  RSImageclass()
        if self.img__obj.open(image_path) is False:
            return False
        width = self.img__obj.GetWidth()
        height = self.img__obj.GetHeight()
        bandcount = self.img__obj.GetBandCount()
        images = numpy.zeros((width, height, bandcount))
        for band in range(0,bandcount):
            band_img = self.__Read_band_data_to_numpy_array(band+1,0,0,width,height,self.img__obj)
            if band_img is False:
                return False
            images[:,:,band] = band_img
        return images

    def __Read_Image_band_data_to_numpy_array(self,bandindex,xoff,yoff,width,height,image_path):
        return True

    def __unpack_gdal_data(self,GDALDataType,offsetvaluestr,width,height):

        if GDALDataType is 2:  # GDT_UInt16
            offsetvalue = struct.unpack('H' * width * height, offsetvaluestr)
        elif GDALDataType is 3:  # GDT_Int16
            offsetvalue = struct.unpack('h' * width * height, offsetvaluestr)
        elif GDALDataType is 6:  # GDT_Float32
            offsetvalue = struct.unpack('f' * width * height, offsetvaluestr)
        elif GDALDataType is 1:  # GDT_Byte = 1
            offsetvalue = struct.unpack('B' * width * height, offsetvaluestr)
        else:
            basic.outputlogMessage('error: not support datatype currently')
            return False
        return offsetvalue


    def __Read_band_data_to_numpy_array(self,bandindex,xoff,yoff,width,height,image_obj=None):
        if image_obj is None:
            image_obj = self.img__obj
        offsetvaluestr = image_obj.ReadbandData(bandindex,xoff,yoff,width,height,image_obj.GetGDALDataType())  #first band offset, may be xoffset
        if offsetvaluestr is False:
            return False
        # offsetvalue = None
        # print image_obj.GetGDALDataType()
        offsetvalue = self.__unpack_gdal_data(image_obj.GetGDALDataType(),offsetvaluestr,width,height)
        if offsetvalue is False:
            return False
        return numpy.asarray(offsetvalue).reshape(width,height)


    def statistic_element_count(self,value,myarray):
        loc_nodata= numpy.where(numpy.fabs(myarray-value)<0.001)
        loc_nodatanum = numpy.array(loc_nodata).size
        return loc_nodatanum

    def statistic_not_element_count(self,not_value,myarray):
        loc_not_value = numpy.where(numpy.fabs(myarray - not_value)>0.0001)
        loc_not_value_num = numpy.array(loc_not_value).size
        return loc_not_value_num

    def statistic_pixel_count(self,pixel_value,RSImageclass_object):

        return True

    def compose_two_image(self,main_image,second_image,nodata):

        if io_function.is_file_exist(main_image) is False:
            return False
        if io_function.is_file_exist(second_image) is False:
            return False
        main_img =  RSImageclass()
        if main_img.open(main_image) is False:
            return False
        width_main = main_img.GetWidth()
        height_main = main_img.GetHeight()
        bandcount_main = main_img.GetBandCount()

        sec_img =  RSImageclass()
        if sec_img.open(second_image) is False:
            return False
        width_sec = sec_img.GetWidth()
        height_sec = sec_img.GetHeight()
        bandcount_sec = sec_img.GetBandCount()

        if width_main!=width_sec or height_main!=height_sec or bandcount_main!=bandcount_sec:
            basic.outputlogMessage('Error: The dimension of two composed images is different')
            return False
        if main_img.GetGDALDataType() != sec_img.GetGDALDataType() or main_img.GetGDALDataType() != 6:
            basic.outputlogMessage('Error: The Data type of two composed imagaes is different or is not float')
            return False

        outputfile = io_function.get_name_by_adding_tail(main_image,'comp')
        imagenew = RSImageclass()
        width = width_main
        height = height_main
        if not imagenew.New(outputfile,width,height,bandcount_main ,main_img.GetGDALDataType()):
            return False
        for i in range(0,bandcount_main):
            bandindex = i+1
            band_main_str = main_img.ReadbandData(bandindex,0,0,width,height,main_img.GetGDALDataType())
            band_sec_str =  sec_img.ReadbandData(bandindex,0,0,width,height,sec_img.GetGDALDataType())

            band_main_data  = struct.unpack('f'*width*height, band_main_str)
            band_main_numpy = numpy.asarray(band_main_data)

            band_sec_data  = struct.unpack('f'*width*height, band_sec_str)
            band_sec_numpy = numpy.asarray(band_sec_data)

            compose_loc = numpy.where( (numpy.fabs(band_main_numpy-nodata)<0.0001) & (numpy.fabs(band_sec_numpy-nodata)>0.0001))
            band_main_numpy[compose_loc] = band_sec_numpy[compose_loc]
            basic.outputlogMessage('outputfortest2: compose_loc_num = %d'%numpy.array(compose_loc).size)

            templist = band_main_numpy.tolist()
            band_composed_str = struct.pack('%sf'%width*height,*templist)
            if imagenew.WritebandData(bandindex,0,0,width,height,band_composed_str,imagenew.GetGDALDataType()) is False:
                return False
            imagenew.SetBandNoDataValue(bandindex,nodata)

        imagenew.SetGeoTransform(main_img.GetGeoTransform())
        imagenew.SetProjection(main_img.GetProjection())

        main_img = None
        sec_img =None
        imagenew = None

        return outputfile