TensorFlow无法找到文件求助:读取NIST数据集图片失败
Troubleshooting "Image Not Found" Error When Loading NIST Dataset for Model Training
First off, I feel your pain—there’s nothing more frustrating than knowing a file exists but your code refuses to recognize it. Let’s walk through the most common fixes for this issue, using your code snippet as a starting point:
Your Current Code (for reference)
import os import cv2 import tensorflow as tf upper_level_dirs = open("/Users/cam/reader/top_level_dirs") upper_level_dirs = upper_level_dirs.read().split() print(upper_level_dirs) file_names = [] labe...
Top Fixes to Try
Verify Paths from
top_level_dirsAre Accurate- First, check if the paths stored in
top_level_dirsare absolute paths (starting with/on Mac/Linux) or relative. If they’re relative, your code’s working directory might not match what you expect. Runprint(os.getcwd())right after importingosto confirm where your code is executing from. - Pick one path from
upper_level_dirs, copy it into your terminal, and runls [path](Mac/Linux) ordir [path](Windows) to make sure the system can find the images. Watch out for hidden spaces, typos, or mismatched capitalization—even Mac’s case-insensitive filesystem can trip up code in rare cases.
- First, check if the paths stored in
Use
os.path.join()for Safe Path Concatenation- If you’re building full image paths with manual string concatenation (like
dir_path + "/" + img_name), stop right now. This often leads to missing or extra path separators, which break file access. Replace it withos.path.join()—it handles system-specific separators automatically:for dir_path in upper_level_dirs: # Skip empty lines from the top_level_dirs file if not dir_path: continue # Iterate through files in the directory for img_file in os.listdir(dir_path): full_img_path = os.path.join(dir_path, img_file) # Test if cv2 can load the image img = cv2.imread(full_img_path) if img is None: print(f"FAILED TO LOAD: {full_img_path}") else: file_names.append(full_img_path) # Add your label logic here - This will print exactly which paths are failing, so you can debug specific entries instead of guessing.
- If you’re building full image paths with manual string concatenation (like
Check File Permissions
- Even if a file exists, your user account might not have permission to read it. In the terminal, run
ls -l [full_image_path]to check permissions. Look for therflag in the user section (the first set of three characters). If it’s missing, fix it with:# Fix a single file chmod +r /path/to/your/image.png # Fix an entire directory recursively chmod -R +r /path/to/your/nist/directory
- Even if a file exists, your user account might not have permission to read it. In the terminal, run
Rule Out cv2-Specific Issues
cv2.imread()returnsNonesilently when it can’t find or load a file—no error message by default. To confirm it’s not a cv2 limitation, try loading a problematic image with PIL instead:from PIL import Image import traceback test_path = "path/to/a/failing/image.png" try: with Image.open(test_path) as img: img.verify() # Validates the file is a proper image print(f"PIL successfully loaded {test_path}") except Exception as e: print(f"PIL failed to load {test_path}:") traceback.print_exc()- If PIL can load it, the issue is with cv2 (maybe a missing codec for the image format). If it fails too, the path or file itself is the problem.
TensorFlow-Specific Checks (If Using TF for Loading)
- If you plan to use TensorFlow’s
tf.datapipeline later, make sure:- Paths are passed as Python strings (not bytes or other types).
- Avoid special characters (like spaces or non-ASCII characters) in paths—TF can struggle with these sometimes.
- Use
tf.io.read_file()with error handling to catch issues early:def load_image(path): try: img_raw = tf.io.read_file(path) img = tf.image.decode_png(img_raw, channels=1) # Adjust for NIST's format return img except tf.errors.InvalidArgumentError: print(f"TF failed to load: {path.numpy().decode('utf-8')}") return None
- If you plan to use TensorFlow’s
Try these steps one by one—chances are the issue is a simple path typo or permission problem that’s easy to fix once you pinpoint it.
内容的提问来源于stack exchange,提问作者Cam Parra
相关产品推荐
相关产品推荐

