You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 test folder: If the test directory 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 test folder 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 the test folder if it doesn't exist. The exist_ok=True flag prevents errors if the folder already exists.
  • os.path.basename(img_path): Grabs just the filename (like image1.jpg) from the full path samples/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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:07:12