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

OpenCV图像捕获后无法实时在文件夹显示问题求助

问题

我用OpenCV写了一段代码,用来捕获图像并保存到指定文件夹,但程序运行时,保存的图像要等程序停止后才会在文件夹里显示。我希望捕获一张就立即在文件夹里看到,然后继续捕获下一张。试过用线程解决,但没效果。

代码如下:

import cv2
import os
import time

save_folder = 'row_photos'
cap = cv2.VideoCapture(0)
interval = 10
start_time = int(time.time())


while True:
    _, frame = cap.read()

    belt = frame[209:327, 137:530]  # cordinates of the belt
    gray_frame = cv2.cvtColor(belt, cv2.COLOR_BGR2GRAY)  # to detect th eframe we will change the color to gray

    _, threshold = cv2.threshold(gray_frame, 80, 255,cv2.THRESH_BINARY)  # inorder to ignore bachground part we will give some threshould value to it

    contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for cnt in contours:
        (x, y, w, h) = cv2.boundingRect(cnt)
        # calculate Area
        area = cv2.contourArea(cnt)

        cv2.rectangle(belt, (x, y), (x + w, y + h), (255, 0, 0), 2)
        cv2.putText(belt, str(area), (x, y), 1, 1, (0, 255, 0))

    cv2.imshow("belt", belt)

    elapsed_time = int(time.time()) - start_time
    
    if elapsed_time >= interval:
        image_name = time.strftime("%Y%m%d%H%M%S") + ".jpg"
        save_path = os.path.join(save_folder, image_name)
        cv2.imwrite(save_path, belt)
        time.sleep(0.01)
        # cv2.imshow(save_path)
        print("Image saved as", save_path)
        start_time = time.time()
    
    if cv2.waitKey(1) == 27:
        break

cap.release()
cv2.destroyAllwindows()
解决方案

问题根源是操作系统的文件系统缓存机制:cv2.imwrite执行后,数据仅写入系统缓存,并未立即同步到磁盘,所以文件夹中看不到新文件,直到程序退出时系统才统一刷新缓存。

解决核心是写完文件后手动强制刷新缓存,确保数据立即落地磁盘。同时修正代码中的小错误,避免额外问题。

修改后的代码:

import cv2
import os
import time

save_folder = 'row_photos'
# 提前创建保存目录,避免首次保存报错
if not os.path.exists(save_folder):
    os.makedirs(save_folder)

cap = cv2.VideoCapture(0)
interval = 10
start_time = int(time.time())


while True:
    _, frame = cap.read()

    belt = frame[209:327, 137:530]  # 传送带区域坐标
    gray_frame = cv2.cvtColor(belt, cv2.COLOR_BGR2GRAY)  # 转为灰度图用于检测

    _, threshold = cv2.threshold(gray_frame, 80, 255, cv2.THRESH_BINARY)  # 二值化过滤背景

    contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for cnt in contours:
        (x, y, w, h) = cv2.boundingRect(cnt)
        area = cv2.contourArea(cnt)  # 计算轮廓面积

        cv2.rectangle(belt, (x, y), (x + w, y + h), (255, 0, 0), 2)
        cv2.putText(belt, str(area), (x, y), 1, 1, (0, 255, 0))

    cv2.imshow("belt", belt)

    elapsed_time = int(time.time()) - start_time
    
    if elapsed_time >= interval:
        image_name = time.strftime("%Y%m%d%H%M%S") + ".jpg"
        save_path = os.path.join(save_folder, image_name)
        # 写入图像文件
        cv2.imwrite(save_path, belt)
        # 强制刷新缓存到磁盘,确保文件立即可见
        with open(save_path, 'rb') as f:
            os.fsync(f.fileno())
        print("Image saved as", save_path)
        start_time = time.time()
    
    if cv2.waitKey(1) == 27:
        break

cap.release()
cv2.destroyAllWindows()  # 修正拼写错误
关键说明
  • os.fsync(f.fileno())会强制将文件缓存中的数据同步到磁盘,确保新保存的图像立即在文件夹中显示。
  • 提前创建保存目录,避免第一次保存时因目录不存在抛出异常。
  • 修正了destroyAllwindows()的拼写错误,保证程序退出时能正确销毁所有窗口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:05:40