mi-task/utils/bar-sky/sky_ratio_analyzer.py

71 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import os
import argparse
def analyze_sky_ratio(image_path, threshold=200, debug=False):
"""
分析图片中白色天空占整个图片的比例
参数:
image_path: 图片路径
threshold: 灰度阈值用于区分天空和非天空区域默认为200较亮的像素
debug: 是否显示处理过程中的图像,用于调试
返回:
sky_ratio: 天空占比0-1之间的浮点数
"""
# 读取图片
img = cv2.imread(image_path)
if img is None:
raise ValueError(f"无法读取图片: {image_path}")
# 转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用阈值分割天空区域(天空通常是图像中较亮的部分)
_, sky_mask = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)
# 计算天空区域占比
total_pixels = gray.shape[0] * gray.shape[1]
sky_pixels = np.sum(sky_mask == 255)
sky_ratio = sky_pixels / total_pixels
# 调试模式:显示处理过程图像
if debug:
# 创建可视化结果
# 原图
cv2.imshow('Original Image', img)
# 灰度图
cv2.imshow('Grayscale Image', gray)
# 天空掩码
cv2.imshow('Sky Mask', sky_mask)
# 在原图上标记天空区域
result = img.copy()
result[sky_mask == 255] = [0, 255, 255] # 用黄色标记天空区域
cv2.imshow('Sky Detection Result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
return sky_ratio
def main():
parser = argparse.ArgumentParser(description='分析图片中天空区域占比')
parser.add_argument('image_path', help='图片路径')
parser.add_argument('--threshold', type=int, default=200, help='天空区域的灰度阈值0-255默认为200')
parser.add_argument('--debug', action='store_true', help='显示处理过程图像')
args = parser.parse_args()
try:
sky_ratio = analyze_sky_ratio(args.image_path, args.threshold, args.debug)
print(f"天空区域占比: {sky_ratio:.2%}")
except Exception as e:
print(f"错误: {e}")
if __name__ == "__main__":
main()