我有一张图片需要翻译2500px,1500px以上,我使用了这段代码:
from PIL import Image
img = Image.open('decoupe_test4.tif')
a = 1
b = 0
c = 2500 # +left/-right
d = 0
e = 1
f = 1500 # +up/-down
translate = img.transform(img.size, Image.AFFINE, (a, b, c, d, e, f))
translate.save('translated.tif')
图片的边框没有改变,但内容没有改变,所以我最终得到了这张图片,在右边:
有谁知道如何才能正确翻译所有图像并摆脱这个黑色部分?
谢谢!
以下是整个代码,可能更清楚:
import subprocess
gm = os.path.join('C:\\','OSGeo4W64','bin','gdal_merge.py')
merge_command = ["python", gm, "-o", "mergedB04.tif", "S2A_tile_20170410_31TFJ_0\B04.jp2", "S2A_tile_20170410_31TGH_0\B04.jp2", "S2A_tile_20170410_31TGJ_0\B04.jp2", "S2A_tile_20170420_31TFH_0\B04.jp2", "S2A_tile_20170420_31TFJ_0\B04.jp2", "S2A_tile_20170420_31TGH_0\B04.jp2"]
merge_command2 = ["python", gm, "-o", "mergedB08.tif", "S2A_tile_20170410_31TFJ_0\B08.jp2", "S2A_tile_20170410_31TGH_0\B08.jp2", "S2A_tile_20170410_31TGJ_0\B08.jp2", "S2A_tile_20170420_31TFH_0\B08.jp2", "S2A_tile_20170420_31TFJ_0\B08.jp2", "S2A_tile_20170420_31TGH_0\B08.jp2"]
subprocess.call(merge_command,shell=True)
subprocess.call(merge_command2,shell=True)
from PIL import Image
import rasterio
from rasterio import Affine
outfile = r'test4.tif'
Image.MAX_IMAGE_PIXELS = 1000000000
im = Image.open('mergedB08.tif')
half_the_width = im.size[0] / 2
half_the_height = im.size[1] / 2
decoupe = im.crop(
(
half_the_width - 2500,
half_the_height - 1500,
half_the_width + 2500,
half_the_height + 1500
)
)
decoupe.save('decoupe_test4.tif')
################### test de translation
img = Image.open('decoupe_test4.tif')
a = 1
b = 0
c = 2500 #left/right (i.e. 5/-5)
d = 0
e = 1
f = 1500 #up/down (i.e. 5/-5)
translate = img.transform(img.size, Image.AFFINE, (a, b, c, d, e, f))
translate.save('translated.tif')
# remise dans le bon scr de l'image
profile = {'driver': 'GTiff',
'dtype': 'float32',
'nodata': None,
'width': decoupe.size[0],
'height': decoupe.size[1],
'count': 1,
'crs': {'init': 'epsg:32631'},
'transform': Affine(10.0, 0.0, 704880.000,0.0, -10.0, 4795110.000)
}
profile.update(driver='GTiff')
profile.update(dtype=rasterio.float32)
with rasterio.open('translated.tif') as decoupe_RAS:
RAS = decoupe_RAS.read().astype(float)
with rasterio.open(outfile, 'w', **profile) as dst:
dst.write(RAS.astype(rasterio.float32))
答案 0 :(得分:0)
移动后需要裁剪图像:
img = Image.open('decoupe_test4.tif')
x_shift = 2500
y_shift = 1500
a = 1
b = 0
c = x_shift #left/right (i.e. 5/-5)
d = 0
e = 1
f = y_shift #up/down (i.e. 5/-5)
translate = img.transform(img.size, Image.AFFINE, (a, b, c, d, e, f))
# Calculate the size after cropping
size = (translate.size[0] - x_shift, translate.size[1] - y_shift)
# Crop to the desired size
translate = translate.transform(size, Image.EXTENT, (0, 0, size[0], size[1]))
translate.save('translated.tif')