def cloudColor(inputpath,inputpathcloud,outputDir): basename = os.path.basename(inputpath).split('.')[0] cloudColorTifName = basename + '_cloud_render.tif' cloudColorTifPath = os.path.join(outputDir, cloudColorTifName) colorTable = {1: (255, 255, 255)} UniqueValues.Render(inputpathcloud, colorTable, returnMode='GEOTIFF', outputPath=cloudColorTifPath, isAlpha=True) #云产品切片 pythonPath = globalCfg['python_path'] gdal2tilesPath = globalCfg['gdal2tiles_path'] tileOutRootDir = globalCfg['tile_server_path'] tileTif=cloudColorTifPath tileName=basename+'_cloud' tileOutDir=os.path.join(tileOutRootDir,tileName) if os.path.exists(tileOutDir): shutil.rmtree(tileOutDir) cmd = '%s %s -z %s -w all %s %s' % (pythonPath, gdal2tilesPath, '8-13', tileTif, tileOutDir) os.system(cmd) os.remove(tileTif)
def exportImage(info1, info2, searchTime1, searchTime2, outTif1, outTif2): conn = pymysql.connect(db=globalCfg['database'], user=globalCfg['database_user'], password=globalCfg['database_passwd'], host=globalCfg['database_host'], port=globalCfg['database_port']) cursor1 = conn.cursor() uuidList1 = str(tuple(info1[5])) sqlStr1 = 'SELECT path FROM ' + globalCfg['database_table_export_image'] + \ ' WHERE uuid IN %s;' % uuidList1 cursor1.execute(sqlStr1) sqlRes1 = cursor1.fetchall() cursor1.close() cursor2 = conn.cursor() uuidList2 = str(tuple(info2[5])) sqlStr2 = 'SELECT path FROM ' + globalCfg['database_table_export_image'] + \ ' WHERE uuid IN %s;' % uuidList2 cursor2.execute(sqlStr2) sqlRes2 = cursor2.fetchall() conn.close() # 加载掩膜数据 maskTifPath = os.path.join(globalCfg['depend_path'], 'taihu', '250', 'taihu_mask_utm[0].tif') ds = gdal.Open(maskTifPath, gdal.GA_ReadOnly) maskArray = ds.GetRasterBand(1).ReadAsArray() ds = None map_dir = globalCfg['map_dir'] # 去年当月tif if len(sqlRes2) > 0: firstTifPath = os.path.join(map_dir, sqlRes2[0][0]) firstDs = gdal.Open(firstTifPath, gdal.GA_ReadOnly) width = firstDs.RasterXSize height = firstDs.RasterYSize trans = firstDs.GetGeoTransform() proj = firstDs.GetProjection() frequencyArray = np.zeros((height, width), dtype=np.float) resultArray = np.zeros((height, width), dtype=np.int) for each in sqlRes2: curTifPath = os.path.join(map_dir, each[0]) curDs = gdal.Open(curTifPath, gdal.GA_ReadOnly) curArray = curDs.GetRasterBand(1).ReadAsArray() frequencyArray += curArray curDs = None # 计算当月天数 datetime1 = datetime.strptime(searchTime1, '%Y-%m-%d %H:%M:%S') datetime2 = datetime.strptime(searchTime2, '%Y-%m-%d %H:%M:%S') deltaDays = (datetime2 - datetime1).days + 1 frequencyArray = (frequencyArray / deltaDays) * 100 resultArray[frequencyArray == 0] = 0 resultArray[np.logical_and(frequencyArray > 0, frequencyArray <= 5)] = 1 resultArray[np.logical_and(frequencyArray > 5, frequencyArray <= 10)] = 2 resultArray[frequencyArray > 10] = 3 resultArray[maskArray == 0] = 65535 driver = gdal.GetDriverByName("GTiff") outDs = driver.Create(outTif1, width, height, 1, gdal.GDT_Float32) outDs.SetGeoTransform(trans) outDs.SetProjection(proj) outDs.GetRasterBand(1).WriteArray(resultArray) outDs = None else: print('Not Found Algae.') # 今年当月tif if len(sqlRes1) > 0: firstTifPath = os.path.join(map_dir, sqlRes1[0][0]) firstDs = gdal.Open(firstTifPath, gdal.GA_ReadOnly) width = firstDs.RasterXSize height = firstDs.RasterYSize trans = firstDs.GetGeoTransform() proj = firstDs.GetProjection() frequencyArray = np.zeros((height, width), dtype=np.float) resultArray = np.zeros((height, width), dtype=np.int) for each in sqlRes1: curTifPath = os.path.join(map_dir, each[0]) curDs = gdal.Open(curTifPath, gdal.GA_ReadOnly) curArray = curDs.GetRasterBand(1).ReadAsArray() frequencyArray += curArray curDs = None # 计算当月天数 datetime1 = datetime.strptime(searchTime1, '%Y-%m-%d %H:%M:%S') datetime2 = datetime.strptime(searchTime2, '%Y-%m-%d %H:%M:%S') deltaDays = (datetime2 - datetime1).days + 1 frequencyArray = (frequencyArray / deltaDays) * 100 resultArray[frequencyArray == 0] = 0 resultArray[np.logical_and(frequencyArray > 0, frequencyArray <= 5)] = 1 resultArray[np.logical_and(frequencyArray > 5, frequencyArray <= 10)] = 2 resultArray[frequencyArray > 10] = 3 resultArray[maskArray == 0] = 65535 driver = gdal.GetDriverByName("GTiff") outDs = driver.Create(outTif2, width, height, 1, gdal.GDT_Float32) outDs.SetGeoTransform(trans) outDs.SetProjection(proj) outDs.GetRasterBand(1).WriteArray(resultArray) outDs = None else: print('Not Found Algae.') # 出图 # DateFrame范围 dataFrameBounds = (197833.762, 3419416.355, 277082.543, 3497440.803) tifFileList = [outTif1, outTif2] for each in tifFileList: # 裁切到模板空间大小 clipTifPath = os.path.join( os.path.dirname(each), os.path.basename(each).replace('.tif', '_clip.tif')) ds = gdal.Warp(clipTifPath, each, format='GTiff', outputBounds=dataFrameBounds, dstNodata=65535, xRes=250, yRes=250) ds = None # 右下角终止列(2438) 右下角终止行(2407) activateWidth = 2388 # 有效列数 2004 activateHeight = 2351 # 有效行数 1841 offsetWidth = 51 # 左上角起始列 offsetHeight = 57 # 左上角起始行 colorTable = { 0: (1, 197, 255), 1: (211, 255, 190), 2: (163, 255, 115), 3: (14, 204, 14) } classifyRender = UniqueValues.Render(clipTifPath, colorTable, returnMode='MEM') classifyRgbImageObj = Image.fromarray(classifyRender, mode='RGB') classifyRgbImageObj = classifyRgbImageObj.resize( (activateWidth, activateHeight), Image.NEAREST) classifyRgbResize = np.asarray(classifyRgbImageObj) bgLocation = np.logical_and( classifyRgbResize[:, :, 0] == 255, classifyRgbResize[:, :, 1] == 255, classifyRgbResize[:, :, 2] == 255, ) modulePngPath = os.path.join(globalCfg['depend_path'], 'taihu', 'mould', 'taihu_algae_month1.png') moduleArray = skimage.io.imread(modulePngPath) moduleActivateArray = moduleArray[offsetHeight:offsetHeight + activateHeight, offsetWidth:offsetWidth + activateWidth, :] classifyRgbResizeCopy = np.copy(classifyRgbResize) classifyRgbResizeCopy[:, :, 0][ bgLocation] = moduleActivateArray[:, :, 0][bgLocation] classifyRgbResizeCopy[:, :, 1][ bgLocation] = moduleActivateArray[:, :, 1][bgLocation] classifyRgbResizeCopy[:, :, 2][ bgLocation] = moduleActivateArray[:, :, 2][bgLocation] moduleArray[offsetHeight:offsetHeight + activateHeight, offsetWidth:offsetWidth + activateWidth, 0] \ = classifyRgbResizeCopy[:, :, 0] moduleArray[offsetHeight:offsetHeight + activateHeight, offsetWidth:offsetWidth + activateWidth, 1] \ = classifyRgbResizeCopy[:, :, 1] moduleArray[offsetHeight:offsetHeight + activateHeight, offsetWidth:offsetWidth + activateWidth, 2] \ = classifyRgbResizeCopy[:, :, 2] outImagePath = os.path.join( os.path.dirname(each), os.path.basename(each).replace('.tif', '.jpg')) skimage.io.imsave(outImagePath, moduleArray[:, :, 0:3].astype(np.uint8))
def tileServer(self): """生成对应切片文件""" basename = os.path.basename(self.inputPath).split('.')[0] # 1.假彩色底图切片 falseColor if self.dataIdentify in FALSE_COLOR_COMPOSE.keys(): if FALSE_COLOR_COMPOSE[self.dataIdentify]: falseColorTifName = os.path.basename(self.l2TifPath).replace( '.tif', '_false.tif') falseColorTifPath = os.path.join(self.outputDir, falseColorTifName) if self.dataIdentify in [ 'SENTINEL2A_MSI_10', 'SENTINEL2B_MSI_10', 'SENTINEL2A_MSI_20', 'SENTINEL2B_MSI_20', 'SENTINEL3A_OLCI_300', 'SENTINEL3B_OLCI_300', 'TERRA_MODIS_250', 'AQUA_MODIS_250' ]: RgbComposite.Compose( self.l2TifPath, FALSE_COLOR_COMPOSE[self.dataIdentify], noDataValue=65535, returnMode='GEOTIFF', outputPath=falseColorTifPath, stretchType='LinearPercent', stretchParam=[0], isAlpha=True) else: RgbComposite.Compose( self.l2TifPath, FALSE_COLOR_COMPOSE[self.dataIdentify], noDataValue=0, returnMode='GEOTIFF', outputPath=falseColorTifPath, stretchType='LinearPercent', stretchParam=[0], isAlpha=True) self.tileDict['falseColor'] = { 'tif': falseColorTifPath, 'name': basename + '_falseColor' } # 2.假彩色底图增强切片 falseColor_enhance1 if self.dataIdentify in FALSE_COLOR_COMPOSE.keys(): if FALSE_COLOR_COMPOSE[self.dataIdentify]: fcEnhanceTifName = os.path.basename(self.l2TifPath).replace( '.tif', '_falseEnhance.tif') fcEnhanceTifPath = os.path.join(self.outputDir, fcEnhanceTifName) if self.dataIdentify in [ 'SENTINEL2A_MSI_10', 'SENTINEL2B_MSI_10', 'SENTINEL2A_MSI_20', 'SENTINEL2B_MSI_20', 'SENTINEL3A_OLCI_300', 'SENTINEL3B_OLCI_300', 'TERRA_MODIS_250', 'AQUA_MODIS_250' ]: RgbComposite.Compose( self.l2TifPath, FALSE_COLOR_COMPOSE[self.dataIdentify], noDataValue=65535, returnMode='GEOTIFF', outputPath=fcEnhanceTifPath, stretchType='LinearPercent', stretchParam=[2], isAlpha=True) else: RgbComposite.Compose( self.l2TifPath, FALSE_COLOR_COMPOSE[self.dataIdentify], noDataValue=0, returnMode='GEOTIFF', outputPath=fcEnhanceTifPath, stretchType='LinearPercent', stretchParam=[2], isAlpha=True) self.tileDict['falseColorEnhance'] = { 'tif': fcEnhanceTifPath, 'name': basename + '_falseColor_enhance1' } # 3.真彩色底图切片 trueColor if self.dataIdentify in TRUE_COLOR_COMPOSE.keys(): if TRUE_COLOR_COMPOSE[self.dataIdentify]: trueColorTifName = os.path.basename(self.l2TifPath).replace( '.tif', '_true.tif') trueColorTifPath = os.path.join(self.outputDir, trueColorTifName) if self.dataIdentify in [ 'SENTINEL2A_MSI_10', 'SENTINEL2B_MSI_10', 'SENTINEL2A_MSI_20', 'SENTINEL2B_MSI_20', 'SENTINEL3A_OLCI_300', 'SENTINEL3B_OLCI_300' ]: RgbComposite.Compose(self.l2TifPath, TRUE_COLOR_COMPOSE[self.dataIdentify], noDataValue=65535, returnMode='GEOTIFF', outputPath=trueColorTifPath, stretchType='LinearPercent', stretchParam=[0], isAlpha=True) else: RgbComposite.Compose(self.l2TifPath, TRUE_COLOR_COMPOSE[self.dataIdentify], noDataValue=0, returnMode='GEOTIFF', outputPath=trueColorTifPath, stretchType='LinearPercent', stretchParam=[0], isAlpha=True) self.tileDict['trueColor'] = { 'tif': trueColorTifPath, 'name': basename + '_trueColor' } # 4.真彩色底图增强切片 trueColor_enhance1 if self.dataIdentify in TRUE_COLOR_COMPOSE.keys(): if TRUE_COLOR_COMPOSE[self.dataIdentify]: tcEnhanceTifName = os.path.basename(self.l2TifPath).replace( '.tif', '_trueEnhance.tif') tcEnhanceTifPath = os.path.join(self.outputDir, tcEnhanceTifName) if self.dataIdentify in [ 'SENTINEL2A_MSI_10', 'SENTINEL2B_MSI_10', 'SENTINEL2A_MSI_20', 'SENTINEL2B_MSI_20', 'SENTINEL3A_OLCI_300', 'SENTINEL3B_OLCI_300' ]: RgbComposite.Compose(self.l2TifPath, TRUE_COLOR_COMPOSE[self.dataIdentify], noDataValue=65535, returnMode='GEOTIFF', outputPath=tcEnhanceTifPath, stretchType='LinearPercent', stretchParam=[2], isAlpha=True) else: RgbComposite.Compose(self.l2TifPath, TRUE_COLOR_COMPOSE[self.dataIdentify], noDataValue=0, returnMode='GEOTIFF', outputPath=tcEnhanceTifPath, stretchType='LinearPercent', stretchParam=[2], isAlpha=True) self.tileDict['trueColorEnhance'] = { 'tif': tcEnhanceTifPath, 'name': basename + '_trueColor_enhance1' } # 5.云产品切片 cloud cloudTifName = os.path.basename(self.cloudTifPath).replace( '.tif', '_render.tif') cloudTifPath = os.path.join(self.outputDir, cloudTifName) colorTable = {1: (255, 255, 255)} UniqueValues.Render(self.cloudTifPath, colorTable, returnMode='GEOTIFF', outputPath=cloudTifPath, isAlpha=True) self.tileDict['cloud'] = { 'tif': cloudTifPath, 'name': basename + '_cloud', 'legendType': '1', 'legendColor': [(255, 255, 255)], 'legendName': ['云'] } # 6.蓝藻产品切片 algaeTifName = os.path.basename(self.algaeTifPath).replace( '.tif', '_render.tif') algaeTifPath = os.path.join(self.outputDir, algaeTifName) colorTable = {1: (255, 251, 0)} UniqueValues.Render(self.algaeTifPath, colorTable, returnMode='GEOTIFF', outputPath=algaeTifPath, isAlpha=True) self.tileDict['taihu_algae_ndvi'] = { 'tif': algaeTifPath, 'name': basename + '_taihu_algae_ndvi', 'legendType': '1', 'legendColor': [(255, 251, 0)], 'legendName': ['水华'] } # 7.蓝藻强度产品切片 intensityTifName = os.path.basename(self.intensityTifPath).replace( '.tif', '_render.tif') intensityTifPath = os.path.join(self.outputDir, intensityTifName) colorTable = {1: (0, 255, 102), 2: (255, 255, 0), 3: (255, 153, 0)} UniqueValues.Render(self.intensityTifPath, colorTable, returnMode='GEOTIFF', outputPath=intensityTifPath, isAlpha=True) self.tileDict['algaeClassify'] = { 'tif': intensityTifPath, 'name': basename + '_classify', 'legendType': '1', 'legendColor': [(0, 255, 102), (255, 255, 0), (255, 153, 0)], 'legendName': ['轻度', '中度', '重度'] } # 调用gdal2tiles工具进行切片 pythonPath = globalCfg['python_path'] gdal2tilesPath = globalCfg['gdal2tiles_path'] tileOutRootDir = globalCfg['tile_server_path'] for key in self.tileDict.keys(): tileTif = self.tileDict[key]['tif'] tileOutDir = os.path.join(tileOutRootDir, self.tileDict[key]['name']) if os.path.exists(tileOutDir): shutil.rmtree(tileOutDir) cmd = '%s %s -z %s -w all %s %s' % ( pythonPath, gdal2tilesPath, TILE_LEVEL, tileTif, tileOutDir) os.system(cmd) os.remove(tileTif) self.tileDict[key]['path'] = tileOutDir
def exportWord(jsonPath, productUuid): # 解析当前json中信息 with open(jsonPath, 'r') as f: jsonData = json.load(f) cloud = jsonData['cloud'] # 云量信息 totalArea = jsonData['totalArea'] # 蓝藻总面积 # 生成文字所需信息=============================================================== issue = os.path.basename(jsonPath).split('_')[3] year = int(issue[0:4]) mm = int(issue[4:6]) dd = int(issue[6:8]) hour = int(issue[8:10]) minute = int(issue[10:12]) timeStr = '%d月%d日%d时%d分' % (mm, dd, hour, minute) totalPercent = jsonData['totalPercent'] # 蓝藻总百分比 lakeStat = jsonData['lakeStat'] # 蓝藻面积分布区域 algaeThreshold = jsonData['algaeThreshold'] lakeRegionList = [] for key in lakeStat.keys(): if lakeStat[key] == 1: lakeRegionList.append(LAKE_REGION_NAME[key]) if len(lakeRegionList) == 0: lakeRegionStr = '' elif len(lakeRegionList) == 1: lakeRegionStr = lakeRegionList[0] else: tempList = lakeRegionList[0:-1] lakeRegionStr = '、'.join(tempList) + '和' + lakeRegionList[-1] areaWX = jsonData['adminArea']['wuxi'] areaCZ = jsonData['adminArea']['changzhou'] areaSZ = jsonData['adminArea']['suzhou'] percentWX = jsonData['adminPercent']['wuxi'] percentCZ = jsonData['adminPercent']['changzhou'] percentSZ = jsonData['adminPercent']['suzhou'] areaH = jsonData['highArea'] areaM = jsonData['midArea'] areaL = jsonData['lowArea'] percentH = jsonData['highPercent'] percentM = jsonData['midPercent'] percentL = jsonData['lowPercent'] # 计算期号 nowDatetime = datetime.datetime.strptime(issue[0:8] + '0000', '%Y%m%d%H%M') # 3月以前算上一年期号 if mm < 3: startDatetime = datetime.datetime.strptime(str(year) + '01010000', '%Y%m%d%H%M') else: startDatetime = datetime.datetime.strptime(str(year) + '03010000', '%Y%m%d%H%M') num = (nowDatetime - startDatetime).days + 1 # 期号 label2 = '' label3 = '' # 蓝藻日报文字部分=================================================== # 1.全云 if cloud >= 95: description = '%sEOS/MODIS卫星遥感影像显示(图1),太湖全部被云层覆盖,无法判断蓝藻聚集情况。' % timeStr description2 = '%sEOS/MODIS卫星遥感影像显示,太湖全部被云层覆盖,无法判断蓝藻聚集情况。' % timeStr label1 = '图1 %d年%d月%d日太湖区域卫星遥感影像' % (year, mm, dd) templateID = 1 typeID = 1 # 2.有云无藻 elif 5 < cloud < 95 and totalArea == 0: description = '%sEOS/MODIS卫星遥感影像显示(图1),太湖部分湖区被云层覆盖,无云区域内未发现蓝藻聚集现象。' % timeStr description2 = '%sEOS/MODIS卫星遥感影像显示,太湖部分湖区被云层覆盖,无云区域内未发现蓝藻聚集现象。' % timeStr label1 = '图1 %d年%d月%d日太湖区域卫星遥感影像' % (year, mm, dd) templateID = 1 typeID = 2 # 3.无云无藻 elif cloud <= 5 and totalArea == 0: description = '%sEOS/MODIS卫星遥感影像显示(图1),太湖未发现蓝藻聚集现象。' % timeStr description2 = '%sEOS/MODIS卫星遥感影像显示,太湖未发现蓝藻聚集现象。' % timeStr label1 = '图1 %d年%d月%d日太湖区域卫星遥感影像' % (year, mm, dd) templateID = 1 typeID = 3 # 4.有云有藻 面积不大于300 elif 5 < cloud < 95 and 0 < totalArea <= 300: description = '%sEOS/MODIS卫星遥感影像显示(图1),太湖部分湖区被云层覆盖,无云区域内发现蓝藻聚集面积约%d平方千米(图2),' \ '占全湖总面积的%.1f%%,主要分布在%s。按行政边界划分,无锡水域%d平方千米,占%d%%;常州水域%d平方千米,' \ '占%d%%;苏州水域%d平方千米,占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) description2 = '%sEOS/MODIS卫星遥感影像显示,太湖部分湖区被云层覆盖,无云区域内发现蓝藻聚集面积约%d平方千米,' \ '占全湖总面积的%.1f%%,主要分布在%s。按行政边界划分,无锡水域%d平方千米,占%d%%;常州水域%d平方千米,' \ '占%d%%;苏州水域%d平方千米,占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) label1 = '图1 %d年%d月%d日太湖区域卫星遥感影像' % (year, mm, dd) label2 = '图2 %d年%d月%d日太湖蓝藻遥感监测' % (year, mm, dd) templateID = 2 typeID = 4 # 5.无云有藻 面积不大于300 elif cloud <= 5 and 0 < totalArea <= 300: description = '%sEOS/MODIS卫星遥感影像显示(图1),太湖发现蓝藻聚集面积约%d平方千米(图2),占全湖总面积的%.1f%%,' \ '主要分布在%s。按行政边界划分,无锡水域%d平方千米,占%d%%;常州水域%d平方千米,占%d%%;苏州水域%d平方千米,' \ '占%d%%。'\ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) description2 = '%sEOS/MODIS卫星遥感影像显示,太湖发现蓝藻聚集面积约%d平方千米,占全湖总面积的%.1f%%,' \ '主要分布在%s。按行政边界划分,无锡水域%d平方千米,占%d%%;常州水域%d平方千米,占%d%%;苏州水域%d平方千米,' \ '占%d%%。'\ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) label1 = '图1 %d年%d月%d日太湖区域卫星遥感影像' % (year, mm, dd) label2 = '图2 %d年%d月%d日太湖蓝藻遥感监测' % (year, mm, dd) templateID = 2 typeID = 5 # 6.无云有藻 面积大于300 有高中低聚集区 elif cloud <= 5 and totalArea > 300 and areaH > 0 and areaM > 0 and areaL > 0: description = '%sEOS/MODIS卫星遥感影像显示(图1),太湖发现蓝藻聚集面积约%d平方千米(图2),占全湖总面积的%.1f%%,' \ '主要分布在%s。其中,高、中、低聚集区面积分别约为%d平方千米、%d平方千米和%d平方千米,' \ '占蓝藻总聚集面积的%d%%、%d%%和%d%%(表1、图3)。按行政边界划分,无锡水域%d平方千米,占%d%%;' \ '常州水域%d平方千米,占%d%%;苏州水域%d平方千米,占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaH, areaM, areaL, percentH, percentM, percentL, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) description2 = '%sEOS/MODIS卫星遥感影像显示,太湖发现蓝藻聚集面积约%d平方千米,占全湖总面积的%.1f%%,' \ '主要分布在%s。其中,高、中、低聚集区面积分别约为%d平方千米、%d平方千米和%d平方千米,' \ '占蓝藻总聚集面积的%d%%、%d%%和%d%%。按行政边界划分,无锡水域%d平方千米,占%d%%;' \ '常州水域%d平方千米,占%d%%;苏州水域%d平方千米,占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaH, areaM, areaL, percentH, percentM, percentL, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) label1 = '图1 %d年%d月%d日太湖区域卫星遥感影像' % (year, mm, dd) label2 = '图2 %d年%d月%d日太湖蓝藻遥感监测' % (year, mm, dd) label3 = '图3 %d年%d月%d日太湖蓝藻聚集强度分级' % (year, mm, dd) templateID = 3 typeID = 5 # 7.无云有藻 面积大于300 无高聚集区 有中低聚集区 elif cloud <= 5 and totalArea > 300 and areaH == 0 and areaM > 0 and areaL > 0: description = '%sEOS/MODIS卫星遥感影像显示(图1),太湖发现蓝藻聚集面积约%d平方千米(图2),占全湖总面积的%.1f%%,' \ '主要分布在%s。其中,无高聚集区,中、低聚集区面积分别约为%d平方千米和%d平方千米,占蓝藻总聚集面积的%d%%和%d%%' \ '(表1、图3)。按行政边界划分,无锡水域%d平方千米,占%d%%;常州水域%d平方千米,占%d%%;苏州水域%d平方千米,' \ '占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaM, areaL, percentM, percentL, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) description2 = '%sEOS/MODIS卫星遥感影像显示,太湖发现蓝藻聚集面积约%d平方千米,占全湖总面积的%.1f%%,' \ '主要分布在%s。其中,无高聚集区,中、低聚集区面积分别约为%d平方千米和%d平方千米,占蓝藻总聚集面积的%d%%和%d%%' \ '。按行政边界划分,无锡水域%d平方千米,占%d%%;常州水域%d平方千米,占%d%%;苏州水域%d平方千米,' \ '占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaM, areaL, percentM, percentL, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) label1 = '图1 %d年%d月%d日太湖区域卫星遥感影像' % (year, mm, dd) label2 = '图2 %d年%d月%d日太湖蓝藻遥感监测' % (year, mm, dd) label3 = '图3 %d年%d月%d日太湖蓝藻聚集强度分级' % (year, mm, dd) templateID = 3 typeID = 5 # 8.无云有藻 面积大于300 无高中聚集区 有低聚集区 elif cloud <= 5 and totalArea > 300 and areaH == 0 and areaM == 0 and areaL > 0: description = '%sEOS/MODIS卫星遥感影像显示(图1),太湖发现蓝藻聚集面积约%d平方千米(图2),占全湖总面积的%.1f%%,' \ '主要分布在%s,全部为低聚集区(表1、图3)。按行政边界划分,无锡水域%d平方千米,占%d%%;常州水域%d平方千米,' \ '占%d%%;苏州水域%d平方千米,占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) description2 = '%sEOS/MODIS卫星遥感影像显示,太湖发现蓝藻聚集面积约%d平方千米,占全湖总面积的%.1f%%,' \ '主要分布在%s,全部为低聚集区。按行政边界划分,无锡水域%d平方千米,占%d%%;常州水域%d平方千米,' \ '占%d%%;苏州水域%d平方千米,占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) label1 = '图1 %d年%d月%d日太湖区域卫星遥感影像' % (year, mm, dd) label2 = '图2 %d年%d月%d日太湖蓝藻遥感监测' % (year, mm, dd) label3 = '图3 %d年%d月%d日太湖蓝藻聚集强度分级' % (year, mm, dd) templateID = 3 typeID = 5 # 9.有云有藻 面积大于300 有高中低聚集区 elif 5 < cloud < 95 and totalArea > 300 and areaH > 0 and areaM > 0 and areaL > 0: description = '%sEOS/MODIS卫星遥感影像显示(图1),太湖部分湖区被云层覆盖,无云区域内发现蓝藻聚集面积约%d平方千米(图2),' \ '占全湖总面积的%.1f%%,主要分布在%s。其中,高、中、低聚集区面积分别约为%d平方千米、%d平方千米和%d平方千米,' \ '占蓝藻总聚集面积的%d%%、%d%%和%d%%(表1、图3)。按行政边界划分,无锡水域%d平方千米,占%d%%;' \ '常州水域%d平方千米,占%d%%;苏州水域%d平方千米,占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaH, areaM, areaL, percentH, percentM, percentL, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) description2 = '%sEOS/MODIS卫星遥感影像显示,太湖部分湖区被云层覆盖,无云区域内发现蓝藻聚集面积约%d平方千米,' \ '占全湖总面积的%.1f%%,主要分布在%s。其中,高、中、低聚集区面积分别约为%d平方千米、%d平方千米和%d平方千米,' \ '占蓝藻总聚集面积的%d%%、%d%%和%d%%。按行政边界划分,无锡水域%d平方千米,占%d%%;' \ '常州水域%d平方千米,占%d%%;苏州水域%d平方千米,占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaH, areaM, areaL, percentH, percentM, percentL, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) label1 = '图1 %d年%d月%d日太湖区域卫星遥感影像' % (year, mm, dd) label2 = '图2 %d年%d月%d日太湖蓝藻遥感监测' % (year, mm, dd) label3 = '图3 %d年%d月%d日太湖蓝藻聚集强度分级' % (year, mm, dd) templateID = 3 typeID = 4 # 10.有云有藻 面积大于300 无高聚集区 有中低聚集区 elif 5 < cloud < 95 and totalArea > 300 and areaH == 0 and areaM > 0 and areaL > 0: description = '%sEOS/MODIS卫星遥感影像显示(图1),太湖部分湖区被云层覆盖,无云区域内发现蓝藻聚集面积约%d平方千米(图2),' \ '占全湖总面积的%.1f%%,主要分布在%s。其中,无高聚集区,中、低聚集区面积约分别约为%d平方千米和%d平方千米,' \ '占蓝藻总聚集面积的%d%%和%d%%(表1、图3)。按行政边界划分,无锡水域%d平方千米,占%d%%;常州水域%d平方千米,' \ '占%d%%;苏州水域%d平方千米,占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaM, areaL, percentM, percentL, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) description2 = '%sEOS/MODIS卫星遥感影像显示,太湖部分湖区被云层覆盖,无云区域内发现蓝藻聚集面积约%d平方千米,' \ '占全湖总面积的%.1f%%,主要分布在%s。其中,无高聚集区,中、低聚集区面积约分别约为%d平方千米和%d平方千米,' \ '占蓝藻总聚集面积的%d%%和%d%%。按行政边界划分,无锡水域%d平方千米,占%d%%;常州水域%d平方千米,' \ '占%d%%;苏州水域%d平方千米,占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaM, areaL, percentM, percentL, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) label1 = '图1 %d年%d月%d日太湖区域卫星遥感影像' % (year, mm, dd) label2 = '图2 %d年%d月%d日太湖蓝藻遥感监测' % (year, mm, dd) label3 = '图3 %d年%d月%d日太湖蓝藻聚集强度分级' % (year, mm, dd) templateID = 3 typeID = 4 # 11.有云有藻 面积大于300 无高中聚集区 有低聚集区 elif 5 < cloud < 95 and totalArea > 300 and areaH == 0 and areaM == 0 and areaL > 0: description = '%sEOS/MODIS卫星遥感影像显示(图1),太湖部分湖区被云层覆盖,无云区域内发现蓝藻聚集面积约%d平方千米(图2),' \ '占全湖总面积的%.1f%%,主要分布在%s,全部为低聚集区(表1、图3)。按行政边界划分,无锡水域%d平方千米,占%d%%;' \ '常州水域%d平方千米,占%d%%;苏州水域%d平方千米,占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) description2 = '%sEOS/MODIS卫星遥感影像显示,太湖部分湖区被云层覆盖,无云区域内发现蓝藻聚集面积约%d平方千米,' \ '占全湖总面积的%.1f%%,主要分布在%s,全部为低聚集区。按行政边界划分,无锡水域%d平方千米,占%d%%;' \ '常州水域%d平方千米,占%d%%;苏州水域%d平方千米,占%d%%。' \ % (timeStr, totalArea, totalPercent, lakeRegionStr, areaWX, percentWX, areaCZ, percentCZ, areaSZ, percentSZ) label1 = '图1 %d年%d月%d日太湖区域卫星遥感影像' % (year, mm, dd) label2 = '图2 %d年%d月%d日太湖蓝藻遥感监测' % (year, mm, dd) label3 = '图3 %d年%d月%d日太湖蓝藻聚集强度分级' % (year, mm, dd) templateID = 3 typeID = 4 else: print('No Match Found!!!') return print(description) # 生成文件==================================================== # 1.生成日报 replaceText = {'year': year, 'num': num, 'mm': mm, 'dd': dd, 'description': description, 'label1': label1, 'label2': label2, 'label3': label3, 'areaH': areaH, 'areaM': areaM, 'areaL': areaL, 'totalArea': totalArea, 'percentH': percentH, 'percentM': percentM, 'percentL': percentL} dependDir = globalCfg['depend_path'] templateDir = os.path.join(dependDir, 'word') templatePath = os.path.join(templateDir, 'report_daily' + str(templateID) + '.docx') tpl = DocxTemplate(templatePath) tpl.render(replaceText) jsonBaseName = os.path.basename(jsonPath) outputDir = os.path.dirname(jsonPath) outWordName = jsonBaseName.replace('.json', '.docx') outWordPath = os.path.join(outputDir, outWordName) picturePath1 = os.path.join(outputDir, jsonBaseName.replace('.json', '_reportImg1_noPoints.jpg')) picturePath2 = os.path.join(outputDir, jsonBaseName.replace('.json', '_reportImg2.jpg')) picturePath3 = os.path.join(outputDir, jsonBaseName.replace('.json', '_reportImg3.jpg')) if not (os.path.exists(picturePath1) and os.path.exists(picturePath2) and os.path.exists(picturePath2)): print('Cannot Find JPG File!!!') return if templateID == 1: replacePic = {"template_picture1.jpg": picturePath1} elif templateID == 2: replacePic = {"template_picture1.jpg": picturePath1, "template_picture2.jpg": picturePath2} elif templateID == 3: replacePic = {"template_picture1.jpg": picturePath1, "template_picture2.jpg": picturePath2, "template_picture3.jpg": picturePath3} else: replacePic = {} for key in replacePic.keys(): tpl.replace_pic(key, replacePic[key]) if os.path.exists(outWordPath): os.remove(outWordPath) tpl.save(outWordPath) # 2.生成推送所需txt第一段文字,剩余两段文字后续添加 outTxtName = jsonBaseName.replace('.json', '.txt') outTxtPath = os.path.join(outputDir, outTxtName) with open(outTxtPath, 'w') as f: f.write(description2) # 3.生成EXCEL xls_num = num xls_date = str(year) + '/' + str(mm) + '/' + str(dd) xls_time = '%s时%s分' % (str(hour), str(minute)) xls_threshold = str(algaeThreshold) xls_ndviMax = str(jsonData['ndviMax']) xls_ndviMin = str(jsonData['ndviMin']) xls_ndviMean = str(jsonData['ndviMean']) xls_boundary = str(jsonData['boundaryThreshold']) xls_area = '' if typeID == 4 or typeID == 5: xls_area = str(totalArea) xls_algae_area = '' if typeID == 2 or typeID == 3: xls_algae_area = '0' elif typeID == 4 or typeID == 5: xls_algae_area = str(totalArea) xls_high = '' if totalArea >= 300 and areaH > 0: xls_high = str(areaH) xls_mid = '' if totalArea >= 300 and areaM > 0: xls_mid = str(areaM) xls_low = '' if totalArea >= 300 and areaL > 0: xls_low = str(areaL) xls_region = lakeRegionStr xls_cloud = str(cloud) if cloud > 50 and totalArea == 0: xls_activate = '0' else: xls_activate = '1' xls_explain = str(typeID) xls_weather = '' if cloud <= 5: xls_cloud_cover = '无覆盖' elif cloud >= 95: xls_cloud_cover = '全部覆盖' else: xls_cloud_cover = '部分覆盖' xls_total_percent = '%.2f%%' % totalPercent xls_intensity_threshold = '' if totalArea >= 300: xls_intensity_threshold = '%.3f-%.3f,%.3f-%.3f,%.3f-%.3f' \ % (jsonData['ndviMin'], jsonData['insThreshold1'], jsonData['insThreshold1'], jsonData['insThreshold2'], jsonData['insThreshold2'], jsonData['ndviMax']) outXlsxName = jsonBaseName.replace('.json', '.xlsx') outXlsxPath = os.path.join(outputDir, outXlsxName) if os.path.exists(outXlsxPath): os.remove(outXlsxPath) workBook = xlsxwriter.Workbook(outXlsxPath) sheet = workBook.add_worksheet() writeTable = {'A1': '报告期数', 'A2': xls_num, 'B1': '日期', 'B2': xls_date, 'C1': '时间', 'C2': xls_time, 'D1': 'NDVI阈值', 'D2': xls_threshold, 'E1': 'NDVI最大值(蓝藻区域)', 'E2': xls_ndviMax, 'F1': 'NDVI最小值(蓝藻区域)', 'F2': xls_ndviMin, 'G1': 'NDVI均值(蓝藻区域)', 'G2': xls_ndviMean, 'H1': '边界缩放', 'H2': xls_boundary, 'I1': '面积(km2)无云无藻不填', 'I2': xls_area, 'J1': '蓝藻面积(无云无藻填0,全云不填,其他按面积填)', 'J2': xls_algae_area, 'K1': '高聚区面积', 'K2': xls_high, 'L1': '中聚区面积', 'L2': xls_mid, 'M1': '低聚区面积', 'M2': xls_low, 'N1': '分布范围(竺山湖、梅梁湖、贡湖、西部沿岸、南部沿岸、东部沿岸和湖心区)', 'N2': xls_region, 'O1': '云量', 'O2': xls_cloud, 'P1': '是否为有效监测(云量超过50%并且没有监测到蓝藻算无效,1为有效,0为无效)', 'P2': xls_activate, 'Q1': '说明(1全云;2有云无藻;3无云无藻;4有云有藻;5无云有藻)', 'Q2': xls_explain, 'R1': '天气', 'R2': xls_weather, 'S1': '是否被云覆盖(无覆盖、全部覆盖、部分覆盖)', 'S2': xls_cloud_cover, 'T1': '水华面积百分比', 'T2': xls_total_percent, 'U1': 'NDVI分级阈值', 'U2': xls_intensity_threshold } format1 = workBook.add_format({'align': 'center', 'font_size': 10, 'valign': 'vcenter', 'text_wrap': 1}) for key in writeTable.keys(): sheet.write(key, writeTable[key], format1) sheet.set_row(0, 60) sheet.set_column('A:M', 8.85) sheet.set_column('N:N', 73) sheet.set_column('P:P', 73) sheet.set_column('Q:Q', 60) sheet.set_column('S:S', 44) sheet.set_column('T:T', 15) sheet.set_column('U:U', 40) workBook.close() # 4.生成EXCEL_WX writeTable2 = {'A1': '报告期数', 'A2': xls_num, 'B1': '日期', 'B2': xls_date, 'C1': '时间', 'C2': xls_time, 'D1': 'NDVI阈值', 'D2': xls_threshold, 'E1': '边界缩放', 'E2': xls_boundary, 'F1': '面积(km2)无云无藻不填', 'F2': xls_area, } outXlsxWxName = jsonBaseName.replace('.json', '_wx.xlsx') outXlsxWxPath = os.path.join(outputDir, outXlsxWxName) if os.path.exists(outXlsxWxPath): os.remove(outXlsxWxPath) workBook2 = xlsxwriter.Workbook(outXlsxWxPath) sheet2 = workBook2.add_worksheet() format2 = workBook2.add_format({'align': 'center', 'font_size': 10, 'valign': 'vcenter', 'text_wrap': 1}) for key in writeTable2.keys(): sheet2.write(key, writeTable2[key], format2) sheet.set_row(0, 60) sheet.set_column('A:F', 9) workBook2.close() # 转pdf供前端查看 Windows无法测试=================================================== outPdfDir = os.path.join(globalCfg['taihu_report_remote'], issue[0:8]) if not os.path.exists(outPdfDir): os.makedirs(outPdfDir) cmdStr = 'libreoffice6.3 --headless --convert-to pdf:writer_pdf_Export ' + outWordPath + ' --outdir ' + outPdfDir print(cmdStr) try: os.system(cmdStr) print('Convert PDF Success.') except Exception as e: print(e) # 信息入库========================================================= conn = pymysql.connect( db=globalCfg['database'], user=globalCfg['database_user'], password=globalCfg['database_passwd'], host=globalCfg['database_host'], port=globalCfg['database_port'] ) # t_water_report_taihu cursor = conn.cursor() algaeTifName = os.path.basename(jsonPath).replace('.json', '.tif') db_uuid = str(uuid.uuid4()) db_date = issue[0:4] + '-' + issue[4:6] + '-' + issue[6:8] db_number = str(num) db_description = description db_label1 = '' db_label2 = '' db_label3 = '' db_image1 = '' db_image2 = '' db_image3 = '' db_high_area = '' db_mid_area = '' db_low_area = '' db_total_area = '' db_high_percent = '' db_mid_percent = '' db_low_percent = '' db_total_percent = '' db_image = algaeTifName db_title = '太湖蓝藻水华卫星遥感监测日报' db_time_modify = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) if templateID == 1: db_label1 = label1 db_image1 = picturePath1.replace('\\', '/').replace('/mnt/resource/', '') elif templateID == 2: db_label1 = label1 db_image1 = picturePath1.replace('\\', '/').replace('/mnt/resource/', '') db_label2 = label2 db_image2 = picturePath2.replace('\\', '/').replace('/mnt/resource/', '') elif templateID == 3: db_label1 = label1 db_image1 = picturePath1.replace('\\', '/').replace('/mnt/resource/', '') db_label2 = label2 db_image2 = picturePath2.replace('\\', '/').replace('/mnt/resource/', '') db_label3 = label3 db_image3 = picturePath3.replace('\\', '/').replace('/mnt/resource/', '') db_high_area = str(areaH) db_mid_area = str(areaM) db_low_area = str(areaL) db_total_area = str(totalArea) db_total_percent = '100.0' db_high_percent = str(percentH) db_mid_percent = str(percentM) db_low_percent = str(percentL) else: pass # 查找是否已存在 sqlStr = 'SELECT * FROM ' + globalCfg['database_table_report_taihu'] + \ ' WHERE image=%s and is_deleted=0;' cursor.execute(sqlStr, algaeTifName) sqlRes = cursor.fetchall() if len(sqlRes) > 0: # 更新 sqlStr = 'UPDATE ' + globalCfg['database_table_report_taihu'] + \ ' SET date=%s,number=%s,description=%s,image1=%s,image2=%s,image3=%s,label1=%s,label2=%s,label3=%s,' \ 'high_area=%s,mid_area=%s,low_area=%s,total_area=%s,high_percent=%s,mid_percent=%s,low_percent=%s,' \ 'total_percent=%s,title=%s,time_modify=%s WHERE image=%s;' sqlData = (db_date, db_number, db_description, db_image1, db_image2, db_image3, db_label1, db_label2, db_label3, db_high_area, db_mid_area, db_low_area, db_total_area, db_high_percent, db_mid_percent, db_low_percent, db_total_percent, db_title, db_time_modify, db_image) cursor.execute(sqlStr, sqlData) conn.commit() else: # 插入 sqlStr = 'INSERT INTO ' + globalCfg['database_table_report_taihu'] + \ ' (uuid,date,number,description,image1,image2,image3,label1,label2,label3,high_area,' \ 'mid_area,low_area,total_area,high_percent,mid_percent,low_percent,total_percent,is_deleted,' \ 'is_default,image,title,time_modify) VALUES ' \ '(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);' sqlData = (db_uuid, db_date, db_number, db_description, db_image1, db_image2, db_image3, db_label1, db_label2, db_label3, db_high_area, db_mid_area, db_low_area, db_total_area, db_high_percent, db_mid_percent, db_low_percent, db_total_percent, 0, 0, db_image, db_title, db_time_modify) cursor.execute(sqlStr, sqlData) conn.commit() # t_water_taihu_modis # 查找是否已存在 sqlStr = 'SELECT * FROM ' + globalCfg['database_table_report_taihu_info'] + \ ' WHERE image_uuid=%s;' cursor.execute(sqlStr, productUuid) sqlRes = cursor.fetchall() db_date = '%s-%s-%s %s:%s' % (issue[0:4], issue[4:6], issue[6:8], issue[8:10], issue[10:12]) regionArea = jsonData['regionArea'] area_zsh = str(regionArea['zhushanhu']) area_mlh = str(regionArea['meilianghu']) area_gh = str(regionArea['gonghu']) area_xbya = str(regionArea['westCoast']) area_nbya = str(regionArea['southCoast']) area_hxq = str(regionArea['centerLake']) area_dbya = str(regionArea['eastCoast']) area_dth = str(regionArea['eastTaihu']) db_region_area = ','.join([area_zsh, area_mlh, area_gh, area_xbya, area_nbya, area_hxq, area_dbya, area_dth]) if len(sqlRes) > 0: # 更新 sqlStr = 'UPDATE ' + globalCfg['database_table_report_taihu_info'] + \ ' SET number=%s,date=%s,ndvi_threshold=%s,ndvi_max=%s,ndvi_min=%s,ndvi_mean=%s,boundary=%s,area=%s,' \ 'region_area=%s,high_area=%s,mid_area=%s,low_area=%s,cloud=%s,type=%s,is_activate=%s,ndvi_grade=%s ' \ 'WHERE image_uuid=%s;' sqlData = (xls_num, db_date, xls_threshold, xls_ndviMax, xls_ndviMin, xls_ndviMean, xls_boundary, str(totalArea), db_region_area, str(areaH), str(areaM), str(areaL), xls_cloud, xls_explain, xls_activate, xls_intensity_threshold, productUuid) cursor.execute(sqlStr, sqlData) conn.commit() else: sqlStr = 'INSERT INTO ' + globalCfg['database_table_report_taihu_info'] + \ ' (number,date,ndvi_threshold,ndvi_max,ndvi_min,ndvi_mean,boundary,area,region_area,high_area,' \ 'mid_area,low_area,cloud,type,is_activate,ndvi_grade,image_uuid) ' \ 'VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);' sqlData = (xls_num, db_date, xls_threshold, xls_ndviMax, xls_ndviMin, xls_ndviMean, xls_boundary, str(totalArea), db_region_area, str(areaH), str(areaM), str(areaL), xls_cloud, xls_explain, xls_activate, xls_intensity_threshold, productUuid) cursor.execute(sqlStr, sqlData) conn.commit() # 更新t_export_image信息 sqlStr = 'SELECT * FROM ' + globalCfg['database_table_export_image'] + \ ' WHERE uuid=%s and is_deleted=0;' cursor.execute(sqlStr, productUuid) sqlRes = cursor.fetchall() if len(sqlRes) > 0: sqlStr = 'UPDATE ' + globalCfg['database_table_export_image'] + \ ' SET area=%s,threshold=%s WHERE uuid=%s;' sqlData = (totalArea, algaeThreshold, productUuid) cursor.execute(sqlStr, sqlData) conn.commit() else: pass cursor.close() conn.close() # 更新切片============================================================== tileDict = {} basename = '_'.join(jsonBaseName.split('_')[0:7]) # 1.蓝藻产品切片 algaeTifPath = os.path.join(outputDir, jsonBaseName.replace('.json', '.tif')) algaeTifRender = os.path.join(outputDir, jsonBaseName.replace('.json', '_render.tif')) colorTable = {1: (255, 251, 0)} UniqueValues.Render(algaeTifPath, colorTable, returnMode='GEOTIFF', outputPath=algaeTifRender, isAlpha=True) tileDict['taihu_algae_ndvi'] = {'tif': algaeTifRender, 'name': basename + '_taihu_algae_ndvi', 'legendType': '1', 'legendColor': [(255, 251, 0)], 'legendName': ['水华']} # 2.蓝藻强度产品切片 intensityTifPath = os.path.join(outputDir, jsonBaseName.replace('_ndvi.json', '_intensity.tif')) intensityTifRender = os.path.join(outputDir, jsonBaseName.replace('_ndvi.json', '_intensity_render.tif')) colorTable = {1: (0, 255, 102), 2: (255, 255, 0), 3: (255, 153, 0)} UniqueValues.Render(intensityTifPath, colorTable, returnMode='GEOTIFF', outputPath=intensityTifRender, isAlpha=True) tileDict['algaeClassify'] = {'tif': intensityTifRender, 'name': basename + '_classify', 'legendType': '1', 'legendColor': [(0, 255, 102), (255, 255, 0), (255, 153, 0)], 'legendName': ['轻度', '中度', '重度']} # 调用gdal2tiles工具进行切片 pythonPath = globalCfg['python_path'] gdal2tilesPath = globalCfg['gdal2tiles_path'] tileOutRootDir = globalCfg['tile_server_path'] for key in tileDict.keys(): tileTif = tileDict[key]['tif'] tileOutDir = os.path.join(tileOutRootDir, tileDict[key]['name']) if os.path.exists(tileOutDir): shutil.rmtree(tileOutDir) cmd = '%s %s -z %s -w all %s %s' % (pythonPath, gdal2tilesPath, TILE_LEVEL, tileTif, tileOutDir) os.system(cmd) os.remove(tileTif) tileDict[key]['path'] = tileOutDir
def exportImage(jsonPath): """生成后续所需所有专题图""" tempDir = os.path.dirname(jsonPath) jsonBaseName = os.path.basename(jsonPath) # 1.出专题图 # 专题图相关文件 l2TifPath = os.path.join(tempDir, jsonBaseName.replace('ndvi.json', 'ndvi.l2.tif')) # 原始数据 algaeTifPath = os.path.join(tempDir, jsonBaseName.replace('ndvi.json', 'ndvi.tif')) # 蓝藻产品 intensityTifPath = os.path.join(tempDir, jsonBaseName.replace( 'ndvi.json', 'intensity.tif')) # 强度产品 if not os.path.isfile(l2TifPath): print('Cannot Find %s' % l2TifPath) return if not os.path.isfile(algaeTifPath): print('Cannot Find %s' % algaeTifPath) return if not os.path.isfile(intensityTifPath): print('Cannot Find %s' % intensityTifPath) return # mxd数据框范围 (195203.762, 3420416.355, 280082.543, 3498433.803) utm_zone_51N # mxd数据框范围 (12284297.415195609, 3516083.924476728, 12369297.415195609, 3438583.924476728) Albers dataFrameBounds = (195203.762, 3420416.355, 280082.543, 3498433.803) # 相关文件以数据框进行放缩 TODO 取消写临时文件到硬盘 l2ClipPath = os.path.join( tempDir, jsonBaseName.replace('ndvi.json', 'ndvi.l2_tmp.tif')) algaeClipPath = os.path.join( tempDir, jsonBaseName.replace('ndvi.json', 'ndvi_tmp.tif')) intensityClipPath = os.path.join( tempDir, jsonBaseName.replace('ndvi.json', 'intensity_tmp.tif')) if os.path.exists(l2ClipPath): os.remove(l2ClipPath) if os.path.exists(algaeClipPath): os.remove(algaeClipPath) if os.path.exists(intensityClipPath): os.remove(intensityClipPath) # 裁切到模板空间大小 ds = gdal.Warp(l2ClipPath, l2TifPath, format='GTiff', outputBounds=dataFrameBounds, dstNodata=65535, xRes=250, yRes=250) ds = None ds = gdal.Warp(algaeClipPath, algaeTifPath, format='GTiff', outputBounds=dataFrameBounds, dstNodata=0, xRes=250, yRes=250) ds = None ds = gdal.Warp(intensityClipPath, intensityTifPath, format='GTiff', outputBounds=dataFrameBounds, dstNodata=0, xRes=250, yRes=250) ds = None # 太湖蓝藻监测的模板有效嵌入信息: # 右下角终止列(2055) 右下角终止行(1893) activateWidth = 2004 # 有效列数 2004 activateHeight = 1841 # 有效行数 1841 offsetWidth = 52 # 左上角起始列 offsetHeight = 53 # 左上角起始行 # 运算三种模板所需的有效数据范围内rgb数组 1.假彩色 2.蓝藻二值 3.聚集强度 # 假彩色 falseColorRgb = RgbComposite.Compose(l2ClipPath, (1, 2, 1), noDataValue=65535, returnMode='MEM') falseColorImageObj = Image.fromarray(falseColorRgb, mode='RGB') falseColorImageObj = falseColorImageObj.resize( (activateWidth, activateHeight), Image.NEAREST) falseColorRgbResize = np.asarray(falseColorImageObj) # 蓝藻rgb colorTable = {1: (229, 250, 5)} algaeRgb = np.copy(falseColorRgb) # 拷贝背景数组 algaeRender = UniqueValues.Render(algaeClipPath, colorTable, returnMode='MEM') invalidLoc = np.logical_and(algaeRender[:, :, 0] == 255, algaeRender[:, :, 1] == 255, algaeRender[:, :, 2] == 255) algaeRgb[:, :, 0][~invalidLoc] = algaeRender[:, :, 0][~invalidLoc] algaeRgb[:, :, 1][~invalidLoc] = algaeRender[:, :, 1][~invalidLoc] algaeRgb[:, :, 2][~invalidLoc] = algaeRender[:, :, 2][~invalidLoc] algaeRgbImageObj = Image.fromarray(algaeRgb, mode='RGB') algaeRgbImageObj = algaeRgbImageObj.resize((activateWidth, activateHeight), Image.NEAREST) algaeRgbResize = np.asarray(algaeRgbImageObj) # 聚集强度 colorTable = {1: (0, 255, 102), 2: (255, 254, 0), 3: (255, 153, 0)} intensityRgb = np.copy(falseColorRgb) # 拷贝背景数组 intensityRender = UniqueValues.Render(intensityClipPath, colorTable, returnMode='MEM') invalidLoc = np.logical_and(intensityRender[:, :, 0] == 255, intensityRender[:, :, 1] == 255, intensityRender[:, :, 2] == 255) intensityRgb[:, :, 0][~invalidLoc] = intensityRender[:, :, 0][~invalidLoc] intensityRgb[:, :, 1][~invalidLoc] = intensityRender[:, :, 1][~invalidLoc] intensityRgb[:, :, 2][~invalidLoc] = intensityRender[:, :, 2][~invalidLoc] intensityRgbImageObj = Image.fromarray(intensityRgb, mode='RGB') intensityRgbImageObj = intensityRgbImageObj.resize( (activateWidth, activateHeight), Image.NEAREST) intensityRgbResize = np.asarray(intensityRgbImageObj) # 循环出图 出图信息存储在字典中 outImagePath1 = os.path.join( tempDir, jsonBaseName.replace('ndvi.json', 'ndvi_reportImg1_noPoints.jpg')) outImagePath2 = os.path.join( tempDir, jsonBaseName.replace('ndvi.json', 'ndvi_reportImg1.jpg')) outImagePath3 = os.path.join( tempDir, jsonBaseName.replace('ndvi.json', 'ndvi_reportImg2_noPoints.jpg')) outImagePath4 = os.path.join( tempDir, jsonBaseName.replace('ndvi.json', 'ndvi_reportImg2.jpg')) outImagePath5 = os.path.join( tempDir, jsonBaseName.replace('ndvi.json', 'ndvi_reportImg3_noPoints.jpg')) outImagePath6 = os.path.join( tempDir, jsonBaseName.replace('ndvi.json', 'ndvi_reportImg3.jpg')) mouldDependDir = os.path.join(globalCfg['depend_path'], 'taihu', 'mould') mouldPath1 = os.path.join(mouldDependDir, 'taihu_algae_mould1.png') mouldPath2 = os.path.join(mouldDependDir, 'taihu_algae_mould1_point.png') mouldPath3 = os.path.join(mouldDependDir, 'taihu_algae_mould2.png') mouldPath4 = os.path.join(mouldDependDir, 'taihu_algae_mould2_point.png') mouldPath5 = os.path.join(mouldDependDir, 'taihu_algae_mould3.png') mouldPath6 = os.path.join(mouldDependDir, 'taihu_algae_mould3_point.png') mouldDict = { 'mould1': { 'modulePath': mouldPath1, 'activateArray': falseColorRgbResize, 'outImagePath': outImagePath1 }, 'mould2': { 'modulePath': mouldPath2, 'activateArray': falseColorRgbResize, 'outImagePath': outImagePath2 }, 'mould3': { 'modulePath': mouldPath3, 'activateArray': algaeRgbResize, 'outImagePath': outImagePath3 }, 'mould4': { 'modulePath': mouldPath4, 'activateArray': algaeRgbResize, 'outImagePath': outImagePath4 }, 'mould5': { 'modulePath': mouldPath5, 'activateArray': intensityRgbResize, 'outImagePath': outImagePath5 }, 'mould6': { 'modulePath': mouldPath6, 'activateArray': intensityRgbResize, 'outImagePath': outImagePath6 } } for each in mouldDict.keys(): moduleArray = skimage.io.imread(mouldDict[each]['modulePath']) # 模板中的非透明位置 alphaLocation = moduleArray[:, :, 3] != 0 moduleArrayBackup = np.copy(moduleArray) # 拷贝模板数组 moduleArray[offsetHeight:offsetHeight + activateHeight, offsetWidth:offsetWidth + activateWidth, 0] \ = mouldDict[each]['activateArray'][:, :, 0] moduleArray[offsetHeight:offsetHeight + activateHeight, offsetWidth:offsetWidth + activateWidth, 1] \ = mouldDict[each]['activateArray'][:, :, 1] moduleArray[offsetHeight:offsetHeight + activateHeight, offsetWidth:offsetWidth + activateWidth, 2] \ = mouldDict[each]['activateArray'][:, :, 2] moduleArray[:, :, 0][alphaLocation] = moduleArrayBackup[:, :, 0][alphaLocation] moduleArray[:, :, 1][alphaLocation] = moduleArrayBackup[:, :, 1][alphaLocation] moduleArray[:, :, 2][alphaLocation] = moduleArrayBackup[:, :, 2][alphaLocation] outImagePath = mouldDict[each]['outImagePath'] skimage.io.imsave(outImagePath, moduleArray[:, :, 0:3].astype(np.uint8)) # 添加左下角水印 fontPath = os.path.join(globalCfg['depend_path'], 'ttf', 'simhei.ttf') # 字体 font = ImageFont.truetype(fontPath, 50) # 水印文本 issue = jsonBaseName.split('_')[3] textMark = '%d年%d月%d日%d时%d分 EOS/MODIS 1B' % \ (int(issue[0:4]), int(issue[4:6]), int(issue[6:8]), int(issue[8:10]), int(issue[10:12])) image = Image.open(outImagePath) draw = ImageDraw.Draw(image) text_location = [300, 1960] draw.text(text_location, textMark, font=font, fill="#000000", spacing=0, align='left') image.save(outImagePath, 'jpeg') # 卫星中心模板大小与以上模板不同 activateWidth = 2004 activateHeight = 1841 offsetWidth = 52 offsetHeight = 63 # 假彩色 falseColorRgb = RgbComposite.Compose(l2ClipPath, (1, 2, 1), noDataValue=65535, returnMode='MEM') falseColorImageObj = Image.fromarray(falseColorRgb, mode='RGB') falseColorImageObj = falseColorImageObj.resize( (activateWidth, activateHeight), Image.NEAREST) falseColorRgbResize = np.asarray(falseColorImageObj) # 蓝藻rgb colorTable = {1: (229, 250, 5)} algaeRgb = np.copy(falseColorRgb) # 拷贝背景数组 algaeRender = UniqueValues.Render(algaeClipPath, colorTable, returnMode='MEM') invalidLoc = np.logical_and(algaeRender[:, :, 0] == 255, algaeRender[:, :, 1] == 255, algaeRender[:, :, 2] == 255) algaeRgb[:, :, 0][~invalidLoc] = algaeRender[:, :, 0][~invalidLoc] algaeRgb[:, :, 1][~invalidLoc] = algaeRender[:, :, 1][~invalidLoc] algaeRgb[:, :, 2][~invalidLoc] = algaeRender[:, :, 2][~invalidLoc] algaeRgbImageObj = Image.fromarray(algaeRgb, mode='RGB') algaeRgbImageObj = algaeRgbImageObj.resize((activateWidth, activateHeight), Image.NEAREST) algaeRgbResize = np.asarray(algaeRgbImageObj) # 聚集强度 colorTable = {1: (0, 255, 102), 2: (255, 254, 0), 3: (255, 153, 0)} intensityRgb = np.copy(falseColorRgb) # 拷贝背景数组 intensityRender = UniqueValues.Render(intensityClipPath, colorTable, returnMode='MEM') invalidLoc = np.logical_and(intensityRender[:, :, 0] == 255, intensityRender[:, :, 1] == 255, intensityRender[:, :, 2] == 255) intensityRgb[:, :, 0][~invalidLoc] = intensityRender[:, :, 0][~invalidLoc] intensityRgb[:, :, 1][~invalidLoc] = intensityRender[:, :, 1][~invalidLoc] intensityRgb[:, :, 2][~invalidLoc] = intensityRender[:, :, 2][~invalidLoc] intensityRgbImageObj = Image.fromarray(intensityRgb, mode='RGB') intensityRgbImageObj = intensityRgbImageObj.resize( (activateWidth, activateHeight), Image.NEAREST) intensityRgbResize = np.asarray(intensityRgbImageObj) outImagePath7 = os.path.join( tempDir, jsonBaseName.replace('ndvi.json', 'ndvi_reportImg1_wxzx.jpg')) outImagePath8 = os.path.join( tempDir, jsonBaseName.replace('ndvi.json', 'ndvi_reportImg2_wxzx.jpg')) outImagePath9 = os.path.join( tempDir, jsonBaseName.replace('ndvi.json', 'ndvi_reportImg3_wxzx.jpg')) mouldPath7 = os.path.join(mouldDependDir, 'taihu_algae_mould1_wxzx.png') mouldPath8 = os.path.join(mouldDependDir, 'taihu_algae_mould2_wxzx.png') mouldPath9 = os.path.join(mouldDependDir, 'taihu_algae_mould3_wxzx.png') mouldDict = { 'mould7': { 'modulePath': mouldPath7, 'activateArray': falseColorRgbResize, 'outImagePath': outImagePath7 }, 'mould8': { 'modulePath': mouldPath8, 'activateArray': algaeRgbResize, 'outImagePath': outImagePath8 }, 'mould9': { 'modulePath': mouldPath9, 'activateArray': intensityRgbResize, 'outImagePath': outImagePath9 } } for each in mouldDict.keys(): moduleArray = skimage.io.imread(mouldDict[each]['modulePath']) # 模板中的非透明位置 alphaLocation = moduleArray[:, :, 3] != 0 moduleArrayBackup = np.copy(moduleArray) # 拷贝模板数组 moduleArray[offsetHeight:offsetHeight + activateHeight, offsetWidth:offsetWidth + activateWidth, 0] \ = mouldDict[each]['activateArray'][:, :, 0] moduleArray[offsetHeight:offsetHeight + activateHeight, offsetWidth:offsetWidth + activateWidth, 1] \ = mouldDict[each]['activateArray'][:, :, 1] moduleArray[offsetHeight:offsetHeight + activateHeight, offsetWidth:offsetWidth + activateWidth, 2] \ = mouldDict[each]['activateArray'][:, :, 2] moduleArray[:, :, 0][alphaLocation] = moduleArrayBackup[:, :, 0][alphaLocation] moduleArray[:, :, 1][alphaLocation] = moduleArrayBackup[:, :, 1][alphaLocation] moduleArray[:, :, 2][alphaLocation] = moduleArrayBackup[:, :, 2][alphaLocation] outImagePath = mouldDict[each]['outImagePath'] skimage.io.imsave(outImagePath, moduleArray[:, :, 0:3].astype(np.uint8)) # 添加左下角水印 fontPath = os.path.join(globalCfg['depend_path'], 'ttf', 'simhei.ttf') # 字体 font = ImageFont.truetype(fontPath, 50) # 水印文本 issue = jsonBaseName.split('_')[3] textMark = '%d年%d月%d日%d时%d分 EOS/MODIS 1B' % \ (int(issue[0:4]), int(issue[4:6]), int(issue[6:8]), int(issue[8:10]), int(issue[10:12])) image = Image.open(outImagePath) draw = ImageDraw.Draw(image) text_location = [300, 1973] draw.text(text_location, textMark, font=font, fill="#000000", spacing=0, align='left') image.save(outImagePath, 'jpeg') # 删除临时文件 if os.path.exists(l2ClipPath): os.remove(l2ClipPath) if os.path.exists(algaeClipPath): os.remove(algaeClipPath) if os.path.exists(intensityClipPath): os.remove(intensityClipPath)
def exportWord(jsonPath, productUuid): # 解析当前json中信息 with open(jsonPath, 'r') as f: jsonData = json.load(f) cloud = jsonData['cloud'] # 云量信息 totalArea = jsonData['totalArea'] # 蓝藻总面积 # 生成文字所需信息=============================================================== issue = os.path.basename(jsonPath).split('_')[3] year = int(issue[0:4]) month = int(issue[4:6]) day = int(issue[6:8]) hour = int(issue[8:10]) minute = int(issue[10:12]) if hour < 12: apStr = '上午' else: apStr = '下午' totalPercent = jsonData['totalPercent'] # 蓝藻总占比 lakeStat = jsonData['lakeStat'] # 蓝藻面积分布区域 algaeThreshold = jsonData['algaeThreshold'] lakeRegionList = [] lakeRegionStr = '' # 区域描述1 for key in lakeStat.keys(): if lakeStat[key] == 1: lakeRegionList.append(LAKE_REGION_NAME[key]) if len(lakeStat) > 0: lakeRegionStr = '、'.join(lakeRegionList) # 区域描述2 if len(lakeRegionList) == 0: lakeRegionStr2 = '' elif len(lakeRegionList) == 1: lakeRegionStr2 = lakeRegionList[0] else: tempList = lakeRegionList[0:-1] lakeRegionStr2 = '、'.join(tempList) + '和' + lakeRegionList[-1] description = '' # 未会商报告文字部分 description2 = '' # 监测中心每日一报文字部分 # 1.全云 if cloud >= 95: description = '%d月%d日遥感监测结果显示,太湖%s全部被云层覆盖,无法判断蓝藻聚集情况,未会商。' % ( month, day, apStr) description2 = '%d月%d日%d时%d分EOS/MODIS卫星遥感影像显示,太湖全部被云层覆盖,无法判断蓝藻聚集情况。' \ % (month, day, hour, minute) # 2.有云无藻 elif 5 < cloud < 95 and totalArea == 0: description = '%d月%d日遥感监测结果显示,太湖%s部分被云层覆盖,无云区域内未发现蓝藻聚集现象,未会商。' % ( month, day, apStr) description2 = '%d月%d日%d时%d分EOS/MODIS卫星遥感影像显示,太湖部分湖区被云层覆盖,无云区域内未发现蓝藻聚集现象。' \ % (month, day, hour, minute) # 3.无云无藻 elif cloud <= 5 and totalArea == 0: description = '%d月%d日遥感监测结果显示,太湖%s未发现蓝藻聚集现象,未会商。' % (month, day, apStr) description2 = '%d月%d日%d时%d分EOS/MODIS卫星遥感影像显示,太湖未发现蓝藻聚集现象。' % ( month, day, hour, minute) # 4.有云有藻 elif 5 < cloud < 95 and totalArea > 0: description = '%d月%d日遥感监测结果显示,太湖%s部分被云层覆盖,在%s发现蓝藻聚集现象,面积约%d平方千米,占太湖总面积的%.1f%%,' \ '未会商。' % (month, day, apStr, lakeRegionStr, totalArea, totalPercent) description2 = '%d月%d日%d时%d分EOS/MODIS卫星遥感影像显示,太湖部分湖区被云层覆盖,无云区域内发现蓝藻聚集面积约%d平方千米,' \ '主要分布在%s。' % (month, day, hour, minute, totalArea, lakeRegionStr2) # 5.无云有藻 elif cloud <= 5 and totalArea > 0: description = '%d月%d日遥感监测结果显示,太湖%s在%s发现蓝藻聚集现象,面积约%d平方千米,占太湖总面积的%.1f%%,未会商。' \ % (month, day, apStr, lakeRegionStr, totalArea, totalPercent) description2 = '%d月%d日%d时%d分EOS/MODIS卫星遥感影像显示,太湖发现蓝藻聚集面积约%d平方千米,' \ '主要分布%s。' % (month, day, hour, minute, totalArea, lakeRegionStr2) else: pass print(description) print(description2) # 生成word==================================================== # 简报word生成 dependDir = globalCfg['depend_path'] templateDir = os.path.join(dependDir, 'word') templatePath = os.path.join(templateDir, 'report_quick.docx') tpl = DocxTemplate(templatePath) replaceText = {"content": description} tpl.render(replaceText) outputDir = os.path.dirname(jsonPath) jsonBaseName = os.path.basename(jsonPath) outWordName = jsonBaseName.replace('.json', '_quick.docx') outWordPath = os.path.join(outputDir, outWordName) picturePath1 = os.path.join( outputDir, jsonBaseName.replace('.json', '_reportImg1_noPoints.jpg')) picturePath2 = os.path.join( outputDir, jsonBaseName.replace('.json', '_reportImg2.jpg')) if not (os.path.exists(picturePath1) and os.path.exists(picturePath2)): print('Cannot Find JPG File!!!') return replacePic = { "template_picture1.jpg": picturePath1, "template_picture2.jpg": picturePath2 } for key in replacePic.keys(): tpl.replace_pic(key, replacePic[key]) if os.path.exists(outWordPath): os.remove(outWordPath) tpl.save(outWordPath) # 每日一报word生成 templatePath2 = os.path.join(templateDir, 'report_jsem.docx') tpl2 = DocxTemplate(templatePath2) replaceText2 = { "content": description2, "year": str(year), "mm": str(month), "dd": str(day) } tpl2.render(replaceText2) outWordName2 = jsonBaseName.replace('.json', '_jsem.docx') outWordPath2 = os.path.join(outputDir, outWordName2) replacePic2 = { "template_picture1.jpg": picturePath1, } for key in replacePic2.keys(): tpl2.replace_pic(key, replacePic2[key]) if os.path.exists(outWordPath2): os.remove(outWordPath2) tpl2.save(outWordPath2) # 信息入库t_water_report_taihu_quick==================================================== conn = pymysql.connect(db=globalCfg['database'], user=globalCfg['database_user'], password=globalCfg['database_passwd'], host=globalCfg['database_host'], port=globalCfg['database_port']) # 先查询数据库是否有这期数据 cursor = conn.cursor() sqlStr = 'SELECT * FROM ' + globalCfg['database_table_report_taihu_quick'] + \ ' WHERE image=%s and is_deleted=0;' algaeTifName = os.path.basename(jsonPath).replace('.json', '.tif') cursor.execute(sqlStr, algaeTifName) sqlRes = cursor.fetchall() if len(sqlRes) > 0: # 更新 db_image = algaeTifName db_description = description db_image1 = picturePath1.replace('\\', '/').replace('/mnt/resource/', '') db_image2 = picturePath2.replace('\\', '/').replace('/mnt/resource/', '') db_time_modify = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) sqlStr = 'UPDATE ' + globalCfg['database_table_report_taihu_quick'] + \ ' SET description=%s,image1=%s,image2=%s,time_modify=%s WHERE image=%s;' sqlData = (db_description, db_image1, db_image2, db_time_modify, db_image) cursor.execute(sqlStr, sqlData) conn.commit() else: # 插入 db_uuid = str(uuid.uuid4()) db_description = description db_image1 = picturePath1.replace('\\', '/').replace('/mnt/resource/', '') db_image2 = picturePath2.replace('\\', '/').replace('/mnt/resource/', '') db_image = algaeTifName sqlStr = 'INSERT INTO ' + globalCfg['database_table_report_taihu_quick'] + \ ' (uuid,description,image1,image2,image) VALUES (%s,%s,%s,%s,%s);' sqlData = (db_uuid, db_description, db_image1, db_image2, db_image) cursor.execute(sqlStr, sqlData) conn.commit() # 更新t_export_image表信息 sqlStr = 'SELECT * FROM ' + globalCfg['database_table_export_image'] + \ ' WHERE uuid=%s and is_deleted=0;' cursor.execute(sqlStr, productUuid) sqlRes = cursor.fetchall() if len(sqlRes) > 0: sqlStr = 'UPDATE ' + globalCfg['database_table_export_image'] + \ ' SET area=%s,threshold=%s WHERE uuid=%s;' sqlData = (totalArea, algaeThreshold, productUuid) cursor.execute(sqlStr, sqlData) conn.commit() else: pass cursor.close() conn.close() # 更新切片============================================================== tileDict = {} basename = '_'.join(jsonBaseName.split('_')[0:7]) # 1.蓝藻产品切片 algaeTifPath = os.path.join(outputDir, jsonBaseName.replace('.json', '.tif')) algaeTifRender = os.path.join(outputDir, jsonBaseName.replace('.json', '_render.tif')) colorTable = {1: (255, 251, 0)} UniqueValues.Render(algaeTifPath, colorTable, returnMode='GEOTIFF', outputPath=algaeTifRender, isAlpha=True) tileDict['taihu_algae_ndvi'] = { 'tif': algaeTifRender, 'name': basename + '_taihu_algae_ndvi', 'legendType': '1', 'legendColor': [(255, 251, 0)], 'legendName': ['水华'] } # 2.蓝藻强度产品切片 intensityTifPath = os.path.join( outputDir, jsonBaseName.replace('_ndvi.json', '_intensity.tif')) intensityTifRender = os.path.join( outputDir, jsonBaseName.replace('_ndvi.json', '_intensity_render.tif')) colorTable = {1: (0, 255, 102), 2: (255, 255, 0), 3: (255, 153, 0)} UniqueValues.Render(intensityTifPath, colorTable, returnMode='GEOTIFF', outputPath=intensityTifRender, isAlpha=True) tileDict['algaeClassify'] = { 'tif': intensityTifRender, 'name': basename + '_classify', 'legendType': '1', 'legendColor': [(0, 255, 102), (255, 255, 0), (255, 153, 0)], 'legendName': ['轻度', '中度', '重度'] } # 调用gdal2tiles工具进行切片 pythonPath = globalCfg['python_path'] gdal2tilesPath = globalCfg['gdal2tiles_path'] tileOutRootDir = globalCfg['tile_server_path'] for key in tileDict.keys(): tileTif = tileDict[key]['tif'] tileOutDir = os.path.join(tileOutRootDir, tileDict[key]['name']) if os.path.exists(tileOutDir): shutil.rmtree(tileOutDir) cmd = '%s %s -z %s -w all %s %s' % (pythonPath, gdal2tilesPath, TILE_LEVEL, tileTif, tileOutDir) os.system(cmd) os.remove(tileTif) tileDict[key]['path'] = tileOutDir