在研究农情的方向中,作物计数是一个很重要的方向,需要用到很多方法,这里做一个小小的总结
(1)地理栅格数据(tif图片)裁剪并生成带地理坐标的切片
如图需要将下图所示的tif图裁剪并生成切片(截图一部分)
源码来自:地理栅格数据裁剪并生成带地理坐标的切片(gdal)_gdal 切片_点PY的博客-优快云博客
import glob
import os
from tqdm import tqdm
import argparse
import tqdm
from osgeo import gdal
import cv2 as cv
import numpy as np
from PIL import Image
from skimage import io
import gdalTools
def subImg(img, i, j, targetSize, PaddingSize, height, width):
if (i + 1) * targetSize < height and (j + 1) * targetSize < width:
temp_img = img[targetSize * i: targetSize * i + targetSize + PaddingSize,
targetSize * j: targetSize * j + targetSize + PaddingSize, :]
start_x = targetSize * i
start_y = targetSize * j
elif (i + 1) * targetSize < height and (j + 1) * targetSize > width:
temp_img = img[targetSize * i: targetSize * i + targetSize + PaddingSize,
width - targetSize - PaddingSize: width, :]
start_x = targetSize * i
start_y = width - targetSize - PaddingSize
elif (i + 1) * targetSize > height and (j + 1) * targetSize < width:
temp_img = img[height - targetSize - PaddingSize: height,
targetSize * j: targetSize * j + targetSize + PaddingSize, :]
start_x = height - targetSize - PaddingSize
start_y = targetSize * j
else:
temp_img = img[height - targetSize - PaddingSize: height, width - targetSize - PaddingSize: width, :]
start_x = height - targetSize - PaddingSize
start_y = width - targetSize - PaddingSize
return temp_img, (start_x, start_y)
def crop(imgRoot, outRoot, targetSize, PaddingSize, ImgSuffix):
labels_list = glob.glob(f"./{imgRoot}/*.tif") # 在文件夹里匹配目标tif图
# labels_list = ['./data/train2.tif']
imgs_num = len(labels_list)
print("imgs_num:{}".format(labels_list))
os.mkdir(outRoot)
for k in tqdm.tqdm(range(imgs_num)):
# label = cv.imread(labels_list[k])
im_proj, im_geotrans, im_width, im_height, label = gdalTools.read_img(labels_list[k])
label = np.transpose(label, (1, 2, 0))
label = gdalTools.stretch_n(label, 0, 255, lower_percent=5, higher_percent=95)
# print(f'max value: {np.max(label)}')
imgName = os.path.split(labels_list[k])[-1].split('.')[0]
height, width = label.shape[0], label.shape[1]
rows, cols = height // targetSize + 1, width // targetSize + 1
subImg_num = 0
for i in range(rows):
for j in range(cols):
temp_label, start_point = subImg(label, i, j, targetSize, PaddingSize, height, width)
size = targetSize+PaddingSize
start_point = (start_point[1] + size // 2, start_point[0] + size // 2)
tempName = imgName + "_" + str(subImg_num) + ImgSuffix
tempPath = os.path.join(outRoot, tempName)
try:
gen_geoClips(labels_list[k], tempPath, start_point, size=size)
subImg_num += 1