这段代码使用 Python 和 OpenCV 库实现了图像和掩码的加载和加权融合。

  1. 导入模块: 代码首先导入了 osshutilcv2 模块。
  2. 定义路径: 接下来,定义了两个变量 pathApathB,分别存储输入图像和标签图像的路径。
  3. 定义 getFileList 函数: 该函数用于获取指定路径下特定后缀名的文件列表。它接收路径 path 和文件后缀名 endwith 作为参数,使用 os.walk 遍历路径下的所有文件和文件夹,并筛选出以指定后缀名结尾的文件。最后,它将文件的完整路径存储在一个列表中,并按字典顺序进行排序,返回该列表。
  4. 获取文件列表: 代码使用 getFileList 函数分别获取输入图像和标签图像的文件列表,存储在 img_path_listmask_path_list 中。
  5. 定义变量: 代码定义了两个变量 max_countcount,分别表示图像总数和当前显示的图像索引。
  6. 主循环: 代码进入一个无限循环,不断读取和处理图像。
  7. 读取图像和掩码: 使用 cv2.imread 函数读取 img_path_listmask_path_list 中对应索引的图像和掩码。
  8. 图像融合: 代码将图像复制到 merge 变量中,并根据掩码中像素值大于0的位置,对 merge 中对应位置的像素值进行加权融合。
  9. 显示图像: 代码使用 cv2.imshow 函数显示 merge 图像,并设置窗口的名称为 winname
  10. 用户交互: 代码使用 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 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录