2. 图像对灰度化
任务说明
双目立体匹配通常基于灰度图像计算视差,因为灰度图仅保留亮度信息,可降低计算量并避免彩色通道间的干扰。本案例的目标是将一张双目图像(左视图与右视图并排存储)转换为单通道灰度图,并拆分保存为左右两个独立文件,为后续的代价计算、匹配等步骤提供标准输入。
实现方案
使用OpenCV读取图像后,先通过cv2.cvtColor将BGR彩色图转为灰度图;再根据图像宽度均分左右视图,分别保存为left_gray.png与right_gray.png。若输入本身已是灰度图,则直接拆分,不做重复转换。
代码实现
import cv2
import os
def convert_stereo_to_gray(input_path, output_dir="."):
"""
将并排双目图像转换为灰度图并拆分为左右视图。
Args:
input_path: 输入图像路径(左右并排)
output_dir: 输出目录,默认当前目录
Returns:
(left_path, right_path): 保存的左右灰度图路径
"""
# 读取图像(支持彩色或灰度)
img = cv2.imread(input_path, cv2.IMREAD_UNCHANGED)
if img is None:
raise FileNotFoundError(f"无法读取图像: {input_path}")
# 若为彩色图(BGR),转为灰度;若已是灰度则跳过
if len(img.shape) == 3:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
else:
gray = img
h, w = gray.shape
# 双目图像左右等宽
half_w = w // 2
left = gray[:, :half_w]
right = gray[:, half_w:]
# 确保输出目录存在
os.makedirs(output_dir, exist_ok=True)
left_path = os.path.join(output_dir, "left_gray.png")
right_path = os.path.join(output_dir, "right_gray.png")
cv2.imwrite(left_path, left)
cv2.imwrite(right_path, right)
return left_path, right_path
if __name__ == "__main__":
# 示例:输入一张并排双目图像
input_file = "stereo_pair.png" # 请替换为实际图像路径
out_dir = "./gray_output"
lp, rp = convert_stereo_to_gray(input_file, out_dir)
print(f"左视图已保存: {lp}")
print(f"右视图已保存: {rp}")
print(f"灰度图尺寸: {cv2.imread(lp, cv2.IMREAD_GRAYSCALE).shape[::-1]}")
落地与验证
运行方式:安装OpenCV(pip install opencv-python),将双目图像命名为stereo_pair.png置于脚本同目录,执行python stereo_gray.py。
验证方法:程序运行后检查输出目录gray_output下是否生成两个文件。用图像查看器打开left_gray.png与right_gray.png,确认二者均为单通道灰度图,且内容分别对应原始图像的左半部分与右半部分。若原始图像宽度为偶数,左右图宽度应各为原图一半;若为奇数,右图宽度为(w-1)//2,左图宽度为w//2,属正常截断。
判定标准:两张输出图像尺寸正确、无彩色信息(像素通道数为1),且左右视图内容与原始双目图像对应区域一致,即视为通过。