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

Windows10 C盘空间丢失与OpenCV SIFT特征提取问题求助

问题描述
  • 非计算机/数学专业,使用Python+Jupyter Notebook开展学习
  • 当前环境:Python 3.10.9(Anaconda打包)、Jupyter 6.5.2、OpenCV 4.7.0
  • 处理1046张图片(单张大小0.015MB-4.147MB),用SIFT提取图像特征时遇到两个问题:
    1. C盘莫名丢失约10GB空间
    2. 代码运行存在异常

附运行代码:

import cv2
import os
import time
import numpy as np
import pandas as pd

def test_descripteur_v4(df = dataFull, var1 = 'image_path', var2 = 'clean_product_name', 
                        var3 = 'clean_product_category_tree_L_base',  feat_num = 8000):
    sift_keypoints = []
    descriptors = []
    list_products = []
    sift = cv2.SIFT_create(feat_num)
    os.environ["OMP_NUM_THREADS"] = '5'
    
    start = time.time()
    for image, name, cat in zip(df[var1], df[var2], df[var3]):
        color_image = cv2.imread(image)
    
        gray_image = cv2.imread(image, cv2.IMREAD_GRAYSCALE) # convert in gray
        clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) # CLAHE (égalisation adaptative d'histogramme à contraste limité)
        cl1 = clahe.apply(gray_image)
        cl1_gauss = cv2.adaptiveThreshold(cl1,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,35,2) # seuil gaussien adaptatif
        contours, hiérarchie = cv2.findContours(cl1_gauss, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # détection contours
        cl1_smooth_contours = cv2.drawContours(cl1_gauss, contours, 0, (0,255,0), 3)
    
        kp, des = sift.detectAndCompute(cl1_gauss, None)
        sift_keypoints.append(des)
        list_products.append([name, cat])
    
    sift_keypoints_by_img = np.asarray(sift_keypoints, dtype=object)
    sift_keypoints_all    = np.concatenate(sift_keypoints_by_img, axis=0)
    print("Nombre total de descripteurs : ", sift_keypoints_all.shape)

    for i in sift_keypoints:
        descriptors.append(i.shape)
    
    descriptor_df = pd.DataFrame(descriptors, columns = ['descripteurs', 'vector_length'])
    names_df = pd.DataFrame(list_products, columns = ['product_name', 'cat'])
    descriptorNames = pd.concat([descriptor_df, names_df], axis=1).sort_values(by='descripteurs', ascending = False)
    
    end = time.time()-start
    duration = "%15.2f"%end
    
    print('Temps de traitement SIFT descriptor : {} secondes'.format(str(duration)))
    
    return sift_keypoints_by_img, sift_keypoints_all, descriptorNames

问题原因解析与解决建议

一、C盘空间丢失的核心原因

  1. 临时文件堆积
    • Jupyter运行时会在C盘临时目录(C:\Users\[你的用户名]\AppData\Local\Temp)生成大量缓存文件,处理图片时的中间数据、未清理的会话残留会持续占用空间。
    • Anaconda默认的pkgs目录在C盘,未清理的旧包、安装残留会堆积占用空间。
  2. 内存数据未释放+虚拟内存膨胀
    • 代码中存储了所有图片的SIFT特征:单张图片按8000个特征算,每个特征是128维float32数组,单张占约4MB,1046张总占用超4GB;加上未使用的color_image等冗余数据,内存负载过高会触发系统虚拟内存(页面文件)扩容,直接占用C盘空间。
  3. OpenCV隐性缓存
    • OpenCV处理CLAHE、阈值操作时,部分中间结果会写入临时目录,未自动清理。

二、代码运行异常的触发点

  1. 参数默认值未定义
    • 函数参数df = dataFull中,dataFull未在函数外提前定义的话,会直接报NameError。
  2. 图像读取无校验
    • 若图片路径错误或文件损坏,cv2.imread返回None,后续CLAHE、阈值处理会直接报错。
  3. 冗余代码浪费内存
    • color_image和cl1_smooth_contours定义后完全未使用,额外占用内存,可能加剧内存溢出。
  4. 轮廓处理逻辑漏洞
    • 若cv2.findContours未检测到轮廓,cv2.drawContours会报错;且仅绘制索引为0的轮廓,逻辑不符合常规需求。
  5. 内存溢出
    • 所有特征向量存入列表并转为numpy数组,内存占用过高会导致程序卡顿、崩溃。

三、具体修复步骤

针对C盘空间问题

  • 手动清理临时目录:打开C:\Users\[你的用户名]\AppData\Local\Temp,删除未在使用的临时文件。
  • 清理Anaconda缓存:打开Anaconda Prompt,运行conda clean -a,自动清理未使用的包和缓存。
  • 及时关闭Jupyter内核:每次运行完代码后关闭对应会话,释放内存,避免虚拟内存持续占用。

针对代码运行异常问题

  1. 修正参数默认值
    把函数定义改为:

    def test_descripteur_v4(df, var1 = 'image_path', var2 = 'clean_product_name', 
                            var3 = 'clean_product_category_tree_L_base',  feat_num = 8000):
    

    调用时传入dataFull:test_descripteur_v4(dataFull)

  2. 删除冗余代码
    删掉未使用的变量定义:

    # 移除这两行
    color_image = cv2.imread(image)
    cl1_smooth_contours = cv2.drawContours(cl1_gauss, contours, 0, (0,255,0), 3)
    
  3. 增加图像读取校验
    在处理前判断图片是否读取成功:

    gray_image = cv2.imread(image, cv2.IMREAD_GRAYSCALE)
    if gray_image is None:
        print(f"无法读取图片: {image}")
        continue  # 跳过损坏或路径错误的图片
    
  4. 优化内存使用

    • 处理完单张图片后手动释放变量:
      del gray_image, cl1, cl1_gauss, contours, hiérarchie
      
    • 若不需要保留所有单张特征,可边处理边写入本地文件,而非全部存在内存中。
  5. 修复轮廓处理逻辑
    若需要保留轮廓绘制,先判断轮廓是否存在:

    contours, hiérarchie = cv2.findContours(cl1_gauss, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    if contours:
        # 这里根据实际需求处理轮廓,不需要则直接删除这段代码
        cl1_smooth_contours = cv2.drawContours(cl1_gauss, contours, 0, (0,255,0), 3)
    

内容的提问来源于stack exchange,提问作者Dvd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:03:18