我有地理参考tiff,gdalinfo输出:
Driver: GTiff/GeoTIFF
Files: generated.tiff
generated.tiff.aux.xml
Size is 6941, 4886
Coordinate System is `'
GCP Projection =
GEOGCS["WGS 84",
DATUM["WGS_1984",
SPHEROID["WGS 84",6378137,298.257223563,
AUTHORITY["EPSG","7030"]],
AUTHORITY["EPSG","6326"]],
PRIMEM["Greenwich",0],
UNIT["degree",0.0174532925199433],
AUTHORITY["EPSG","4326"]]
GCP[ 0]: Id=1, Info=
(0,0) -> (0.01,0.05886,0)
GCP[ 1]: Id=2, Info=
(6941,0) -> (0.07941,0.05886,0)
GCP[ 2]: Id=3, Info=
(6941,4886) -> (0.07941,0.01,0)
GCP[ 3]: Id=4, Info=
(0,4886) -> (0.01,0.01,0)
Metadata:
AREA_OR_POINT=Area
Software=paint.net 4.0
Image Structure Metadata:
INTERLEAVE=BAND
Corner Coordinates:
Upper Left ( 0.0, 0.0)
Lower Left ( 0.0, 4886.0)
Upper Right ( 6941.0, 0.0)
Lower Right ( 6941.0, 4886.0)
Center ( 3470.5, 2443.0)
第二个文件包含地图标记图像 - 名为marker1.png(36x60像素)。
我想将marker1.png覆盖在上面生成的.tiff之上 - 这样它的左上角位于geotiff文件的坐标0.037,0.025处。在视觉上,结果应该看起来像谷歌地图,顶部有一个标记。
我将如何实现这一目标?
我已经设法部分实现了这一点,但我不确定这是否是正确的道路。
import gdal
gdal.UseExceptions()
s = gdal.Open('generated.tiff')
drv = gdal.GetDriverByName("VRT")
vrt = drv.CreateCopy('test.vrt', s, 0)
band = vrt.GetRasterBand(1)
source_path = 'marker1.png'
source_band = 1
x_size = 36
y_size = 60
x_block = 36
y_block = 1
x_offset = 0
y_offset = 0
x_source_size = 36
y_source_size = 60
dest_x_offset = 2000
dest_y_offset = 2000
x_dest_size = 36
y_dest_size = 60
simple_source = '<SimpleSource><SourceFilename relativeToVRT="1">%s</SourceFilename>' % source_path + \
'<SourceBand>%i</SourceBand>' % source_band + \
'<SourceProperties RasterXSize="%i" RasterYSize="%i" DataType="Byte" BlockXSize="%i" BlockYSize="%i"/>' % (x_size, y_size, x_block, y_block) + \
'<SrcRect xOff="%i" yOff="%i" xSize="%i" ySize="%i"/>' % (x_offset, y_offset, x_source_size, y_source_size) + \
'<DstRect xOff="%i" yOff="%i" xSize="%i" ySize="%i"/></SimpleSource>' % (dest_x_offset, dest_y_offset, x_dest_size, y_dest_size)
band.SetMetadata({'source_0': simple_source}, "new_vrt_sources")
band.SetMetadataItem("NoDataValue", '1')
p = gdal.GetDriverByName("PNG")
p.CreateCopy('result.png', vrt, 0)
vrt = None
这使用像素坐标而不是地理坐标(但转换很容易),但标记图像显示为黑色斑点(但尺寸正确) - 看起来调色板可能有误?
答案 0 :(得分:2)
我尝试了多种不同的方法,没有正常工作 - 颜色错误,透明度错误或不正确。
最后,我在PIL的帮助下完成了这项工作,代码如下。它只是几行,它实际上是可读的(与我用gdal想到的任何东西相反),最重要的是 - 它可以工作。
当然,它可以改进。
from PIL import Image, ImageFont, ImageDraw
from osgeo import gdal,ogr
image = 'generated.tiff'
src_ds = gdal.Open(image)
gt = src_ds.GetGeoTransform() # used to convert geographical coordinates to pixel coordinates
font = ImageFont.truetype("sans-serif.ttf", 16)
img = Image.open(image)
def add_marker (gt, watermark, font, img, mx, my, text):
px = int((mx - gt[0]) / gt[1]) #x pixel
py = int((my - gt[3]) / gt[5]) #y pixel
wmark = Image.open(watermark)
draw = ImageDraw.Draw(wmark)
draw.text((12, 10), text, (0, 0, 0), font=font)
img.paste(wmark, (px, py), wmark)
add_marker(gt, 'marker1.png', font, img, 0.012, 0.0132, "1")
img.save("result.png", "PNG")