簡體   English   中英

將其他Python腳本導入為模塊

[英]Importing other Python scripts as Modules

我目前正在嘗試編寫一個應用程序,該應用程序將視頻分成單獨的幀,然后在視頻中找到人臉並將其提取為.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:“模塊”對象不可調用。 如果我按照你們中某些人的建議進行操作,或者按照標記為“相似”的問題進行操作,則腳本將啟動,但仍然無法正常工作,只能創建文件夾。

您可以通過將if __name__ == "__main__":轉換為新函數def extractor()並導入模塊來運行extractor.py

import extractor;
extractor.extractor();

您還只能使用以下import變體來導入特定名稱(在我們的示例中為extractor()函數):

from extractor import extractor;
extractor();

請查看此鏈接( https://repl.it/repls/MeaslyMerrySymbol ),其中我完成了與您的文件相似的示例導入。

將提取器功能封裝在另一個文件中,例如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文件,並僅調用此函數,但是也可以從其他文件中導入和調用它。

由於您不必傳遞任何參數,因此可以通過extractor.main()調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM