OpenCV imwrite无法将图片保存至目标文件夹问题求助
Fixing Image Saving Issue to the
test Folder Hey there! Let's get your resized images saving correctly to the test folder. The most common culprits here are either the target folder not existing (OpenCV won't create it automatically) or incorrect file paths when saving. Let's break this down and fix your code.
Common Issues & Solutions
- Missing
testfolder: If thetestdirectory doesn't exist,cv2.imwrite()will silently fail without creating it. We need to explicitly create the folder first. - Incorrect save path: You're probably trying to save images using just the filename instead of combining it with the
testfolder path, which means images end up in your current working directory instead of the target folder.
Corrected Full Code
import cv2 import glob import os from tqdm import tqdm # Get all JPG images in samples folder imgs = glob.glob('samples/*.jpg') print('Images files:', imgs) # Set target dimensions width = 100 height = 100 folder = 'test' # Create the test folder if it doesn't exist os.makedirs(folder, exist_ok=True) # Process each image with progress bar for img_path in tqdm(imgs): # Read the image img = cv2.imread(img_path) if img is None: print(f"Warning: Could not read image {img_path}") continue # Resize the image resized_img = cv2.resize(img, (width, height)) # Extract the original filename filename = os.path.basename(img_path) # Create full save path (test/filename.jpg) save_path = os.path.join(folder, filename) # Save the resized image success = cv2.imwrite(save_path, resized_img) if not success: print(f"Warning: Failed to save image to {save_path}") print("Processing complete!")
Key Fixes Explained
os.makedirs(folder, exist_ok=True): This line creates thetestfolder if it doesn't exist. Theexist_ok=Trueflag prevents errors if the folder already exists.os.path.basename(img_path): Grabs just the filename (likeimage1.jpg) from the full pathsamples/image1.jpg.os.path.join(folder, filename): Safely combines the folder path and filename to create a valid save path (e.g.,test/image1.jpg), which works across Windows, macOS, and Linux.- Added error checking for reading/saving images: Helps catch cases where an image can't be read or saved, so you know exactly where things go wrong.
内容的提问来源于stack exchange,提问作者Firis
相关产品推荐
相关产品推荐

