22
10
内容纲要
前两天为了研究隐形数字水印技术,了解了一些OpenCV的用法,涉及到把黑色背景图去掉的方法,别的不多说,直接上代码吧!
import os
import cv2
path = "D:/build/utensilspictureNew" #文件夹目录
# 遍历文件夹及其子文件夹中的文件,并存储在一个列表中
# 输入文件夹路径、空文件列表[]
# 返回 文件列表Filelist,包含文件名(完整路径)
def get_filelist(dir):
newDir = dir
if os.path.isfile(dir):
src = cv2.imread(newDir,1)
tmp = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
_, alpha = cv2.threshold(tmp, 0, 255, cv2.THRESH_BINARY)
b, g, r = cv2.split(src)
rgba = [b, g, r, alpha]
dst = cv2.merge(rgba, 4)
cv2.imwrite(newDir, dst)
print('Done');
elif os.path.isdir(dir):
for s in os.listdir(dir):
newDir=os.path.join(dir,s)
get_filelist(newDir)
get_filelist(path)
代码还包括了如何递归遍历文件夹里的文件夹和文件。