繁体   English   中英

程序没有从while循环写入列表?

[英]Program not writing to list from while loop?

当像素强度差异高于预定义阈值时,我正在尝试将值写入我的VideoFlag列表。 在输出上,但是我的输出'flag.txt'文件为空,我不确定为什么。 有人知道我的代码以什么方式错误吗?

谢谢!

import cv2
import tkinter as tk
from tkinter.filedialog import askopenfilename
import numpy as np 
import os
import matplotlib.pyplot as plt 

MIList =[]
VideoFlag=[]

def frame_diff(prev_frame, cur_frame, next_frame):
    diff_frames1 = cv2.absdiff(next_frame, cur_frame)

    diff_frames2 = cv2.absdiff(cur_frame, prev_frame)

    return cv2.bitwise_and(diff_frames1, diff_frames2)

def get_frame(cap):
    ret, frame = cap.read()
    if ret == True:
        scaling_factor = 1
        frame = cv2.resize(frame, None, fx = scaling_factor, fy = scaling_factor, interpolation = cv2.INTER_AREA)
        return cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)

def moving_average(MIList, n=30) :
    ret = np.cumsum(MIList, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n

def main():

    root = tk.Tk()
    root.withdraw()

    selectedvideo = askopenfilename()
    cap = cv2.VideoCapture(selectedvideo)
    length = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    intlength = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    currentframenumber = cap.get(cv2.CAP_PROP_POS_FRAMES)
    intcurrentframenumber = int(cap.get(cv2.CAP_PROP_POS_FRAMES))
    scaling_factor = 1
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter((selectedvideo + 'motionindexed.avi'),fourcc, 60.0, (640,478), isColor=False)
    with open((selectedvideo + 'threshold' + '.txt'), 'r') as readthreshold:
        threshold = float(readthreshold.readline())

    prev_frame = get_frame(cap)
    cur_frame = get_frame(cap)
    next_frame = get_frame(cap)

    while (cap.isOpened()):

        try:
            cv2.imshow("Object Movement", frame_diff(prev_frame, cur_frame, next_frame))
            prev_frame = cur_frame
            cur_frame = next_frame
            next_frame = get_frame(cap)
            differencesquared = (next_frame-cur_frame)**2
            interframedifference = np.sum(differencesquared)
            MIList.append(interframedifference)
            print(interframedifference)
            if interframedifference >= threshold:
                out.write(cur_frame)
                VideoFlag.append(str(intcurrentframenumber + '|' + 1))
                print(VideoFlag)
            elif interframedifference < threshold:
                VideoFlag.append(str(intcurrentframenumber + '|' + 0))
                print(VideoFlag)

            key = cv2.waitKey(1)
            if key == ord('q'):
                break
        except:
            break

    with open((selectedvideo + 'flag' + '.txt'), 'w') as f:
        for item in VideoFlag:
            f.write(str(item))


    cap.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    # this is called if this code was not imported ... ie it was directly run
    # if this is called, that means there is no GUI already running, so we need to create a root
    root = tk.Tk()
    root.withdraw()
    main()

更换

with open((selectedvideo + 'flag' + '.txt'), 'w') as f:
    for item in VideoFlag:
        f.write(str(item))

# Note that you need to append('a') data to the file instead of writing('w') to it for each iteration. 
# The last line will be empty string and that is what contains finally.
with open((selectedvideo + 'flag' + '.txt'), 'a') as f: 
    for item in VideoFlag:
        f.write(str(item))

将解决问题。

我想我已经解决了我的问题-不管出于何种原因,由于我的append方法中的类型,它都没有运行-我忘了将我的一个整数转换为我认为的字符串,我已经对其进行了重新设计认为这解决了我的问题! 为输入家伙们加油!

import cv2
import tkinter as tk
from tkinter.filedialog import askopenfilename
import numpy as np 
import os
import matplotlib.pyplot as plt 

def frame_diff(prev_frame, cur_frame, next_frame):
    diff_frames1 = cv2.absdiff(next_frame, cur_frame)

    diff_frames2 = cv2.absdiff(cur_frame, prev_frame)

    return cv2.bitwise_and(diff_frames1, diff_frames2)

def get_frame(cap):
    ret, frame = cap.read()
    if ret == True:
        scaling_factor = 1
        frame = cv2.resize(frame, None, fx = scaling_factor, fy = scaling_factor, interpolation = cv2.INTER_AREA)
        return cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)

def main():

    root = tk.Tk()
    root.withdraw()

    MIList = []
    VideoFlag = []
    selectedvideo = askopenfilename()
    cap = cv2.VideoCapture(selectedvideo)
    length = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    intlength = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    currentframenumber = cap.get(cv2.CAP_PROP_POS_FRAMES)
    intcurrentframenumber = int(cap.get(cv2.CAP_PROP_POS_FRAMES))
    scaling_factor = 1
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter((selectedvideo + 'motionindexed.avi'),fourcc, 60.0, (640,478), isColor=False)
    with open((selectedvideo + 'threshold' + '.txt'), 'r') as readthreshold:
        threshold = float(readthreshold.readline())

    prev_frame = get_frame(cap)
    cur_frame = get_frame(cap)
    next_frame = get_frame(cap)

    while (cap.isOpened()):

        try:
            cv2.imshow("Object Movement", frame_diff(prev_frame, cur_frame, next_frame))
            prev_frame = cur_frame
            cur_frame = next_frame
            next_frame = get_frame(cap)
            differencesquared = (next_frame-cur_frame)**2
            interframedifference = np.sum(differencesquared)
            MIList.append(interframedifference)
            print(interframedifference)
            if interframedifference >= threshold:
                out.write(cur_frame)
                VideoFlag.append((str(intcurrentframenumber) + ' ' + '|' + ' ' + '1' + '\n' ))


            elif interframedifference < threshold:
                VideoFlag.append((str(intcurrentframenumber) + ' ' + '|' + ' ' + '0' + ' \n'))



            key = cv2.waitKey(1)
            if key == ord('q'):
                break
        except:
            break

    with open((selectedvideo + 'flag' + '.txt'), 'w') as f:
        for item in VideoFlag:
            f.write((str(item) + '\n'))
        print(VideoFlag)


    cap.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    # this is called if this code was not imported ... ie it was directly run
    # if this is called, that means there is no GUI already running, so we need to create a root
    root = tk.Tk()
    root.withdraw()
    main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM