opencv 如何将三个.py文件中的代码写入一个文件

deikduxw  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(111)

我有3个.py文件,可以将视频分割成帧,对这些帧应用显著性,然后将这些帧组合成一个视频。我希望有一个.py文件可以完成上述所有操作,而不是运行三个单独的文件。我提供了下面的代码。

1. Spliting video.py

import cv2

capture = cv2.VideoCapture('vids/tm_test.mp4')
fps = capture.get(cv2.CAP_PROP_FPS)
print(fps)
frameNr = 0

while True:
    success, frame = capture.read()

    if success:
        cv2.imwrite(f'Output/frame_{frameNr}.jpg', frame)
    else:
        break

    frameNr = frameNr + 1

capture.release()

2. Saliency.py

import cv2
from glob import glob

source = r'Output/*.jpg'

path_to_save = 'images/'
saliency = cv2.saliency.StaticSaliencyFineGrained_create()
def main():
    i = 0
    for fn in glob(source):
        image = cv2.imread(fn)
        (ret, img_sal) = saliency.computeSaliency(image)
        saliencyMap = (img_sal * 255).astype('uint8')
        cv2.imwrite(path_to_save + 'test_salient_tm '+ str(i) + '.jpg', saliencyMap)
        i += 1

if __name__ == '__main__':
    main()
 
3. Combining after saliency.py

import cv2
import os

image_folder = 'images/'
video_name = 'vids/tm_test_salient.mp4'

images = [img for img in os.listdir(image_folder) if img.endswith('.jpg')]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video = cv2.VideoWriter(video_name, fourcc, 56.0, (width, height))

for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))

cv2.destroyAllWindows()
video.release()

我如何将这三个文件合并到一个文件中来执行这些功能。谢谢

gjmwrych

gjmwrych1#

以下是组合的开始。

import cv2
from glob import glob
import os

# globals
capture = cv2.VideoCapture('vids/tm_test.mp4')
saliency = cv2.saliency.StaticSaliencyFineGrained_create()
fps = capture.get(cv2.CAP_PROP_FPS)
source = r'Output/*.jpg'
path_to_save = 'images/'
frameNr = 0
image_folder = 'images/'
video_name = 'vids/tm_test_salient.mp4'

# Functions

# Inputs

# Processing
while True:
    success, frame = capture.read()
    if success:
        cv2.imwrite(f'Output/frame_{frameNr}.jpg', frame)
    else:
        break
    frameNr = frameNr + 1
capture.release()
i = 0
for fn in glob(source):
    image = cv2.imread(fn)
    (ret, img_sal) = saliency.computeSaliency(image)
    saliencyMap = (img_sal * 255).astype('uint8')
    cv2.imwrite(path_to_save + 'test_salient_tm ' + str(i) + '.jpg',
                saliencyMap)
    i += 1

images = [img for img in os.listdir(image_folder) if img.endswith('.jpg')]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video = cv2.VideoWriter(video_name, fourcc, 56.0, (width, height))
for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))
cv2.destroyAllWindows()
video.release()

# Outputs

相关问题