opencv---读写图片一个容易出错的地方( imwrite 函数)

opencv---读写图片一个容易出错的地方( imwrite 函数)

问题:

cv2.imwrite(filename, img) filename 是文件路径,但是必须要确保文件路径存在,否则将无法保存图片,并且也不会报任何错误 !!!

details:

path = os.getcwd()  #  获取当前 python脚本所在的路径 

path = path + "output"

os.path.isdir(path)  # 判断文件夹是否存在

 os.mkdir(path)  # 创建文件夹

读取某路径下的所有图片,依次进行处理后,保存到另外一个文件路径下

# -*- coding:utf-8 -*-
import cv2
import os
import numpy as np

save_path = os.getcwd() + "/output"

if os.path.isdir(save_path) == False:
    os.mkdir(save_path)

for root, dirs, files in os.walk('test_dir'):
    for name in files:
        # 读取图片
        image = cv2.imread(os.path.join(root, name), flags=cv2.IMREAD_GRAYSCALE)
        if image is None or image.shape[0] != image.shape[1] or name[:3] != "tag":
            continue
        shape = [scale * x for x in image.shape]
        output = np.zeros(shape, dtype=np.uint8)
        # 对 output 进行处理 (此处直接等于,不做处理)
        output = image

        # cv2.imwrite(os.path.join(os.getcwd()+'/output', name), output)
        # cv2.imshow("output", output)
        # cv2.waitKey(10)
        cv2.imwrite(os.path.join(save_path, name), output)

发布了26 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/CGJustDoIT/article/details/103808921