python 主程序遍历文件夹里的图片后,调用自定义的 process_image()方法,进入后运行到图像灰度化时,提示image为空None,想不明白,是遍历的结果有错,还是参数传递有错,或是什么?这里好像传入的图片列表路径,而我正真要的是图片路径下的图片数据。请教教我,或请您给看看哪里有写的不对的地方,谢谢各位大老诗
下面是python代码
import cv2
import os
def process_image(image_path):
# 读取图片
img = cv2.imread(image_path)
# 获取前景部分
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnt = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(cnt)
foreground = img[y:y + h, x:x + w]
# 统一改变背景颜色为黑色
background = cv2.imread('black.jpg')
background = cv2.resize(background, (w, h))
foreground = cv2.resize(foreground, (w, h))
mask = cv2.cvtColor(foreground, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(mask, 10, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(thresh)
img1_bg = cv2.bitwise_and(background, background, mask=thresh)
img2_fg = cv2.bitwise_and(foreground, foreground, mask=mask_inv)
dst = cv2.add(img1_bg, img2_fg)
# 统一改变图片分辨率为24*24
dst = cv2.resize(dst, (24, 24))
# 返回处理后的图片
return dst
# 读取文件目录中的每一个文件
path = 'image_folder/'
for filename in os.listdir(path):
if filename.endswith('.jpg'):
image_path = os.path.join(path, filename)
# 处理图片
processed_image = process_image(image_path)
# 保存处理后的图片
cv2.imwrite(os.path.join(path, 'processed_' + filename), processed_image)
if __name__ == '__main__':
# 读取文件夹中的所有文件
folder_path = 'D:/PyCharm_Projects/lab/imagefile' # 给相对路径下的文件夹赋值一个变量名
file_list = os.listdir(folder_path) # 将文件夹变量名及内部文件转为python列表的格式
# 遍历文件列表
for i, fileNames in enumerate(file_list):
# 调用获取图片前景部分,并统一改变背景颜色为黑色,和统一改变图片分辨率为24*24的函数
process_image(fileNames)
报错:
PyDev console: starting.
Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] on win32
runfile('D:/PyCharm_Projects/lab/heoll.py', wdir='D:/PyCharm_Projects/lab')
None
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "D:\PyCharm2021.3\PyCharm 2021.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "D:\PyCharm2021.3\PyCharm 2021.3\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "D:/PyCharm_Projects/lab/heoll.py", line 48, in <module>
process_image(fileNames)
File "D:/PyCharm_Projects/lab/heoll.py", line 10, in process_image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(3.4.8) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function