将其他Python脚本作为模块导入

时间:2019-07-09 14:46:55

标签: python python-3.x

我目前正在尝试编写一个应用程序,该应用程序将视频分割成各个帧,然后在视频中找到人脸并将其提取为.jpg。我将项目拆分为多个文件,分别是负责GUI的app.py和执行工作的extractor.py。

我认为您可以导入以下文件:

import extractor

然后像这样运行它:

extractor()

显然,这似乎不起作用。我还尝试使整个提取器脚本成为一个函数,然后调用该函数,但这也不起作用。

app.py:

import extractor
extractor()

extractor.py:

import cv2
import os
import face_recognition
from PIL import Image
import multiprocessing

try:
    if not os.path.exists('frames'):
        os.makedirs('frames')
except OSError:
    print('Error: Creating directory of frames')

try:
    if not os.path.exists('faces'):
        os.makedirs('faces')
except OSError:
    print('Error: Creating directory of faces')

def extract_frames(video_file_path):
    currentFrame_extract = 1
    video_capture = cv2.VideoCapture(video_file_path)

    while(True):
        ret, frame = video_capture.read()
        if ret == False:
            break
        name = 'frames/frame_' + str(currentFrame_extract) + '.jpg'
        print(f"Extracting Frame {currentFrame_extract}, saving it as Frame_{currentFrame_extract}.jpg")
        cv2.imwrite(name, frame)
        currentFrame_extract += 1

    video_capture.release()
    cv2.destroyAllWindows()
    return currentFrame_extract

def find_faces_a(a):
    i = 0
    currentFrame = 1

    while (True):

        if a > currentFrame:

            image = face_recognition.load_image_file(f"data/frame_{currentFrame}.jpg")
            face_locations = face_recognition.face_locations(image)

            if len(face_locations) >= 1:
                top, right, bottom, left = face_locations[0]

                face_image = image[top:bottom, left:right]
                pil_image = Image.fromarray(face_image)
                pil_image.save(f"faces/face_{currentFrame}.jpg".format(i))
                print(f"Found a face at Frame_{currentFrame}, exporting it as Face_{currentFrame}.jpg")

            currentFrame += 4
        else:
            break

def find_faces_b(a):
    i = 0
    currentFrame = 2

    while (True):

        if a > currentFrame:

            image = face_recognition.load_image_file(f"data/frame_{currentFrame}.jpg")
            face_locations = face_recognition.face_locations(image)

            if len(face_locations) >= 1:
                top, right, bottom, left = face_locations[0]

                face_image = image[top:bottom, left:right]
                pil_image = Image.fromarray(face_image)
                pil_image.save(f"faces/face_{currentFrame}.jpg".format(i))
                print(f"Found a face at Frame_{currentFrame}, exporting it as Face_{currentFrame}.jpg")

            currentFrame += 4
        else:
            break

def find_faces_c(a):
    i = 0
    currentFrame = 3

    while (True):

        if a > currentFrame:

            image = face_recognition.load_image_file(f"data/frame_{currentFrame}.jpg")
            face_locations = face_recognition.face_locations(image)

            if len(face_locations) >= 1:
                top, right, bottom, left = face_locations[0]

                face_image = image[top:bottom, left:right]
                pil_image = Image.fromarray(face_image)
                pil_image.save(f"faces/face_{currentFrame}.jpg".format(i))
                print(f"Found a face at Frame_{currentFrame}, exporting it as Face_{currentFrame}.jpg")

            currentFrame += 4
        else:
            break

def find_faces_d(a):
    i = 0
    currentFrame = 4

    while (True):

        if a > currentFrame:

            image = face_recognition.load_image_file(f"data/frame_{currentFrame}.jpg")
            face_locations = face_recognition.face_locations(image)

            if len(face_locations) >= 1:
                top, right, bottom, left = face_locations[0]

                face_image = image[top:bottom, left:right]
                pil_image = Image.fromarray(face_image)
                pil_image.save(f"faces/face_{currentFrame}.jpg".format(i))
                print(f"Found a face at Frame_{currentFrame}, exporting it as Face_{currentFrame}.jpg")

            currentFrame += 4
        else:
            break

if __name__ == "__main__":

    video_file_path = "Video_3.mp4"
    currentFrame_extract = extract_frames(video_file_path)

    currentFrame_extract = [currentFrame_extract]
    p1 = multiprocessing.Process(target=find_faces_a, args=(currentFrame_extract))
    p2 = multiprocessing.Process(target=find_faces_b, args=(currentFrame_extract))
    p3 = multiprocessing.Process(target=find_faces_c, args=(currentFrame_extract))
    p4 = multiprocessing.Process(target=find_faces_d, args=(currentFrame_extract))

    p1.start()
    p2.start()
    p3.start()
    p4.start()

    p1.join()
    p2.join()
    p3.join()
    p4.join()

    print("Frame extraction and alignment finished successfully.")

我收到错误:TypeError:“模块”对象不可调用。如果我像某些人建议的那样执行此操作,或者按照标记为“相似”的问题进行操作,该脚本将启动,但仍无法正常工作,仅创建文件夹。

3 个答案:

答案 0 :(得分:0)

您可以通过将extractor.py转换为新功能if __name__ == "__main__":并导入模块来运行def extractor()

import extractor;
extractor.extractor();

您还只能使用以下import变体来导入特定名称(在我们的情况下为extractor()函数):

from extractor import extractor;
extractor();

请查看此链接(https://repl.it/repls/MeaslyMerrySymbol),其中我完成了与您的文件相似的示例导入。

答案 1 :(得分:0)

将提取器功能封装在另一个文件中,例如extractor_impl。然后将所有内容放在此文件的函数中:

def extract(video_file_path)
    currentFrame_extract = extract_frames(video_file_path)

    currentFrame_extract = [currentFrame_extract]
    p1 = multiprocessing.Process(target=find_faces_a, args=(currentFrame_extract))
    p2 = multiprocessing.Process(target=find_faces_b, args=(currentFrame_extract))
    p3 = multiprocessing.Process(target=find_faces_c, args=(currentFrame_extract))
    p4 = multiprocessing.Process(target=find_faces_d, args=(currentFrame_extract))

    p1.start()
    p2.start()
    p3.start()
    p4.start()

    p1.join()
    p2.join()
    p3.join()
    p4.join()

    print("Frame extraction and alignment finished successfully.")

然后您可以从提取器文件中导入extractor_impl文件并仅调用此函数,但是您也可以从其他文件中导入和调用它。

答案 2 :(得分:0)

通过extractor.main()进行调用,因为您无需向其传递任何参数。