问题出在将输入图像转换为灰度图像时,没有将数据类型从浮点型转换为无符号8位整型。导致后续的Canny边缘检测函数报错。
以下是修改后的代码:from tifffile import imreadimport numpy as npfrom osgeo import gdal, osrimport cv2# 读取TIFF格式无人机影像数据image_path = 'F:\duneline\dune\dune.tif'output_path = 'overlay_image.tif'image = imread(image_path)# 将输入图像转换为灰度图像gray_image = np.mean(image, axis=2).astype(np.uint8) # 转换数据类型为uint8# 自适应阈值二值化binary = np.zeros_like(gray_image, dtype=np.uint8)window_size = 7 # 窗口大小k = 0.1 # 控制阈值的参数for i in range(window_size//2, gray_image.shape[0]-window_size//2): for j in range(window_size//2, gray_image.shape[1]-window_size//2): window = gray_image[i-window_size//2:i+window_size//2+1, j-window_size//2:j+window_size//2+1] threshold = np.mean(window) - k * np.std(window) if gray_image[i, j] > threshold: binary[i, j] = 255# 使用Canny边缘检测edges = cv2.Canny(gray_image, 30, 100)# 对边缘图像应用形态学操作kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))dilated_edges = cv2.dilate(edges, kernel, iterations=1)closing = cv2.morphologyEx(dilated_edges, cv2.MORPH_CLOSE, kernel, iterations=3)# 配置输出的空间参考信息in_ds = gdal.Open(image_path)projection = in_ds.GetProjection()geotransform = in_ds.GetGeoTransform()# 创建新的输出图像driver = gdal.GetDriverByName('GTiff')out_ds = driver.Create(output_path, image.shape[1], image.shape[0], 1, gdal.GDT_Byte, options=['COMPRESS=NONE']) # 修改数据类型为gdal.GDT_Byte# 设置输出图像的空间参考信息out_ds.SetProjection(projection)out_ds.SetGeoTransform(geotransform)# 将沙脊线部分写入输出图像out_band = out_ds.GetRasterBand(1)out_band.WriteArray(closing.astype(np.uint8)) # 修改为正确的数据类型# 设置颜色表color_table = gdal.ColorTable()color_table.SetColorEntry(0, (0, 0, 0, 0)) # 黑色,对应值为0color_table.SetColorEntry(255, (255, 255, 255, 255)) # 白色,对应值为255out_band.SetColorTable(color_table)# 释放资源out_band.FlushCache()out_ds = Nonein_ds = Noneprint("保存成功!")
请尝试运行修改后的代码,看是否能够成功执行边缘检测并保存图像。
如果回答对你有帮助,请给我一个最佳答案!
|