问题背景:
运行图片灰度增强代码时报错,先后检查了图片的路径、cv2.imread() 函数的格式以及代码逻辑,确认均无误后报错依然无法消失。
代码:
# coding:utf-8
# 图片灰度增强
import math
import cv2 as cv
import numpy as np
import os
# 统计灰度分布
def calc_hist(img):
rows, cols = img.shape[:2]
hist = np.zeros(256, np.uint64)
for r in range(rows):
for c in range(cols):
hist[img[r, c]] += 1
return hist
def equalize_hist(img):
rows, cols = img.shape[:2]
hist = calc_hist(img)
# 计算灰度累积分布
# 注意数据类型为np.uint32,防止溢出
hist_sum = np.zeros([256], np.uint32)
for i in range(256):
if i == 0:
hist_sum[i] = hist[i]
else:
hist_sum[i] = hist[i] + hist_sum[i - 1]
# 输出图像的灰度分布
output_hist = np.zeros(256, np.uint8)
cofficient = 256.0 / (rows * cols)
for i in range(256):
q = cofficient * float(hist_sum[i]) - 1
if q >= 0:
output_hist[i] = math.floor(q)
else:
output_hist[i] = 0
# 输出图像的像素值
output_img = np.zeros([rows, cols], np.uint8)
for r in range(rows):
for c in range(cols):
output_img[r, c] = output_hist[img[r, c]]
return output_img
if __name__ == "__main__":
print('start')
write_dir = '/Users/***/Desktop/距离酒依赖/Gray_train/'
file_list = os.listdir('/Users/***/Desktop/距离酒依赖/train')
len = len(file_list)
for i in range(len):
path = '/Users/***/Desktop/距离酒依赖/train/' + file_list[i]
img = cv.imread(path, 0)
img_equalized = equalize_hist(img)
path_write = write_dir + file_list[i]
cv.imwrite(path_write, np.array(img_equalized))
print('end')
错误信息:
Traceback (most recent call last):
File "/Users/***/Desktop/***.py", line 59, in <module>
img_equalized = equalize_hist(img)
File "/Users/***/Desktop/***.py", line 19, in equalize_hist
rows, cols = img.shape[:2]
AttributeError: 'NoneType' object has no attribute 'shape'
报错的含义是无法得到 img 的长、宽值。实际上,这是由于没有 img 传入equalize_hist (img) 导致的。
但是,我查看了增强图像所在的文件夹后,发现已经生成了一些图像。
因此,我判断这个错误一定是某个图像文件引起的。
于是,我通过在 cv2.imread () 前将图片的路径打印出来以确定到底是哪个文件出现了问题。
if __name__ == "__main__":
print('start')
write_dir = '/Users/fengyifan/Desktop/距离酒依赖/Gray_train/'
file_list = os.listdir('/Users/fengyifan/Desktop/距离酒依赖/train')
len = len(file_list)
for i in range(len):
path = '/Users/fengyifan/Desktop/距离酒依赖/train/' + file_list[i]
print(path)
img = cv.imread(path, 0)
img_equalized = equalize_hist(img)
path_write = write_dir + file_list[i]
cv.imwrite(path_write, np.array(img_equalized))
print('end')
运行结果显示,使程序报错的文件为格式是.DS_store 的一个文件,cv2.imread () 函数无法读取这种格式的文件的,因此程序报错。
据此,我判断只要避开这个文件便可。所以,只需一个 if 判断就解决了程序报错的问题。
if __name__ == "__main__":
print('start')
write_dir = '/Users/***/Desktop/距离酒依赖/Gray_train/'
file_list = os.listdir('/Users/***/Desktop/距离酒依赖/train')
len = len(file_list)
for i in range(len):
path = '/Users/***/Desktop/距离酒依赖/train/' + file_list[i]
if path != '/Users/***/Desktop/距离酒依赖/train/.DS_Store':
img = cv.imread(path, 0)
img_equalized = equalize_hist(img)
path_write = write_dir + file_list[i]
cv.imwrite(path_write, np.array(img_equalized))
print('end')
结果:
成功解决!
知识扩展:
.DS_store 文件: 该文件是 Mac OS 保存文件夹的自定义属性的隐藏文件,如文件的图标位置或背景色,相当于 Windows 的 desktop.ini
文章出处登录后可见!
已经登录?立即刷新