pic should be PIL Image or ndarray. Got <class 'NoneType'>
时间: 2024-12-21 15:24:14 浏览: 2
Python 实现Image和Ndarray互相转换
错误提示"TypeError: pic should be PIL Image or ndarray. Got <class 'NoneType'>"意味着在尝试读取图像时,`cv2.imread()`函数接收到的是`NoneType`而不是预期的PIL Image对象或NumPy数组(ndarray)。这个问题通常是由于图片文件路径无效,或者文件不存在导致的。
解决这个问题的步骤如下:
1. **确认文件是否存在**:
```python
if os.path.exists(f"./save_sketch/{each_name}/{each_image_index}.png"):
print(f"File exists: {f='./save_sketch/{each_name}/{each_image_index}.png'}")
else:
print(f"File not found: {f='./save_sketch/{each_name}/{each_image_index}.png'}")
```
2. **读取图片并转换格式**:
如果文件存在,确保在读取之前正确处理路径:
```python
try:
import cv2
from PIL import Image
each_image_path = f"./save_sketch/{each_name}/{each_image_index}.png"
pil_img = Image.open(each_image_path)
image_cv = np.array(pil_img) # Convert the PIL Image to a NumPy array
# Now you can proceed with further processing on image_cv
except FileNotFoundError:
print(f"File {each_image_path} not found.")
except IOError as e:
print(f"Error reading file {each_image_path}: {e}")
```
这样,如果图片存在,会先尝试打开它,如果不能,则捕获异常并给出相应的反馈。记得检查是否导入了PIL库(`from PIL import Image`),因为`Image.open()`函数需要这个库。
阅读全文