def extract_building_shadow(image, dsm, ground_spacing, radius): shadow_mask = np.zeros_like(image, dtype=np.bool) for i in range(0, image.shape[0], ground_spacing): for j in range(0, image.shape[1], ground_spacing): if not np.any(shadow_mask[i, j]): center = (i, j) ground_height = dsm[i, j] for x, y in spiral_search(center, radius, ground_spacing): if x < 0 or x >= image.shape[0] or y < 0 or y >= image.shape[1]: continue if np.any(shadow_mask[x, y:]): continue height = dsm[x, y] if height > ground_height: shadow_mask[x, y] = True elif height == ground_height: if np.linalg.norm(np.array([x, y]) - np.array(center)) < \ np.linalg.norm(np.array([i, j]) - np.array(center)): shadow_mask[x, y] = True cv2.imwrite(output_path, shadow_mask.astype(np.uint8) * 255) return shadow_mask image = cv2.imread('C:\yingxiang\DJI_20230322140516_0026_V.JPG') dsm_path = 'C:/sanwei/jianmo/Productions/Production_2/Production_2_DSM_part_2_2.tif' dsm_dataset = gdal.Open(dsm_path) output_path = 'C:\yingxiang\mask.png'这段代码为什么运行后不能将掩膜结果保存
时间: 2024-03-17 10:39:46 浏览: 66
这可能是由于在保存 PNG 文件之前,尝试在代码中访问 `output_path` 变量,而此时该变量尚未定义。您可以将 `output_path` 变量的定义移动到函数之前,以确保在访问变量之前它已经存在。例如:
```
output_path = 'C:\yingxiang\mask.png'
def extract_building_shadow(image, dsm, ground_spacing, radius):
shadow_mask = np.zeros_like(image, dtype=np.bool)
for i in range(0, image.shape[0], ground_spacing):
for j in range(0, image.shape[1], ground_spacing):
if not np.any(shadow_mask[i, j]):
center = (i, j)
ground_height = dsm[i, j]
for x, y in spiral_search(center, radius, ground_spacing):
if x < 0 or x >= image.shape[0] or y < 0 or y >= image.shape[1]:
continue
if np.any(shadow_mask[x, y:]):
continue
height = dsm[x, y]
if height > ground_height:
shadow_mask[x, y] = True
elif height == ground_height:
if np.linalg.norm(np.array([x, y]) - np.array(center)) < \
np.linalg.norm(np.array([i, j]) - np.array(center)):
shadow_mask[x, y] = True
cv2.imwrite(output_path, shadow_mask.astype(np.uint8) * 255)
return shadow_mask
image = cv2.imread('C:\yingxiang\DJI_20230322140516_0026_V.JPG')
dsm_path = 'C:/sanwei/jianmo/Productions/Production_2/Production_2_DSM_part_2_2.tif'
dsm_dataset = gdal.Open(dsm_path)
# 调用函数
extract_building_shadow(image, dsm_dataset.ReadAsArray(), 10, 10)
```
请注意,此代码还将 `dsm` 数据集转换为数组,并将其传递给函数。
阅读全文