Python代码解析:使用 OpenCV 加载图像并进行加权融合
这段代码使用 Python 和 OpenCV 库实现了图像和掩码的加载和加权融合。
- 导入模块: 代码首先导入了
os、shutil和cv2模块。 - 定义路径: 接下来,定义了两个变量
pathA和pathB,分别存储输入图像和标签图像的路径。 - 定义 getFileList 函数: 该函数用于获取指定路径下特定后缀名的文件列表。它接收路径
path和文件后缀名endwith作为参数,使用os.walk遍历路径下的所有文件和文件夹,并筛选出以指定后缀名结尾的文件。最后,它将文件的完整路径存储在一个列表中,并按字典顺序进行排序,返回该列表。 - 获取文件列表: 代码使用
getFileList函数分别获取输入图像和标签图像的文件列表,存储在img_path_list和mask_path_list中。 - 定义变量: 代码定义了两个变量
max_count和count,分别表示图像总数和当前显示的图像索引。 - 主循环: 代码进入一个无限循环,不断读取和处理图像。
- 读取图像和掩码: 使用
cv2.imread函数读取img_path_list和mask_path_list中对应索引的图像和掩码。 - 图像融合: 代码将图像复制到
merge变量中,并根据掩码中像素值大于0的位置,对merge中对应位置的像素值进行加权融合。 - 显示图像: 代码使用
cv2.imshow函数显示merge图像,并设置窗口的名称为winname。 - 用户交互: 代码使用
cv2.waitKey函数等待用户的按键输入,并根据按键执行相应的操作:- 按键
1:显示上一张图像。 - 按键
2:显示下一张图像。 - 按键
9:退出程序。
- 按键
代码的具体实现如下:
import os
import shutil
import cv2
pathA = 'D:\Projects\Github\UC_Unet\data\uc\inputs'
pathB = 'D:\Projects\Github\UC_Unet\data\uc\labels'
def getFileList(path:str, endwith:str):
iter = os.walk(path)
path_list = []
for p, d, filelist in iter:
for name in filelist:
if name.endswith(endwith):
path_list.append(os.path.join(p, name))
path_list.sort()
return path_list
img_path_list = getFileList(pathA, '.png')
mask_path_list = getFileList(pathB, '.png')
max_count = len(img_path_list)
count = 0
while True:
img = cv2.imread(img_path_list[count])
mask = cv2.imread(mask_path_list[count])
merge = img.copy()
merge[mask>0] = merge[mask>0] * 0.5 + mask[mask>0] * 0.5
print((img_path_list[count].split('\')[-1], mask_path_list[count].split('\')[-1]))
while True:
cv2.imshow('winname', merge.astype('uint8'))
the_key = cv2.waitKey()
if the_key == ord('1'):
count = max(0, count-1)
break
elif the_key == ord('2'):
count = min(count+1, max_count-1)
break
elif the_key == ord('9'):
exit()
原文地址: http://www.cveoy.top/t/topic/pswX 著作权归作者所有。请勿转载和采集!