示例#1
0
def camera2video():
    capture = cv2.VideoCapture(0)   # 비디오 캡처, video 장치 번호
    # w = int(capture.get(3))
    # h = int(capture.get(4))
    w = 1280
    h = 720
    capture.set(cv2.CAP_PROP_FRAME_WIDTH, w)  # width
    capture.set(cv2.CAP_PROP_FRAME_HEIGHT, h) # height

    savedir = 'datas/videos'            # 저장 경로
    filename = 'output_camera2video'           # 저장 파일 이름
    fps = 20 

    output_filename = savedir + '/' + filename + '.avi'
    fourcc = cv2.VideoWriter_fourcc(*'DIVX')
    out_avi = cv2.VideoWriter(output_filename, fourcc, fps, (w,h))  # video writer object
    output_filename = savedir + '/' + filename + '.mp4'
    fourcc = cv2.VideoWriter_fourcc(*'MP4V')
    out_mp4 = cv2.VideoWriter(output_filename, fourcc, fps, (w,h))  # video writer object
    
    while True:
        ret, frame = capture.read() # camera 읽기
        if ret:
            out_avi.write(frame)
            out_mp4.write(frame)
            cv2.imshow('img', frame)
        if cv2.waitKey(1) > 0: break    # 키보드 입력이 들어오면 종료

    capture.release()       
    out_avi.release()
    out_mp4.release()
    cv2.destroyAllWindows()
示例#2
0
def save_video(outname):
    "Count the number of frames"

    # Directory name
    DIR = './results/' + outname + '/overlay/frames/'

    # Number of frames
    nframes = len([
        name for name in os.listdir(DIR)
        if os.path.isfile(os.path.join(DIR, name))
    ])

    # Frame size
    frame_size = cv2.imread(DIR + 'img0.jpg').shape
    nx, ny = frame_size[0], frame_size[1]

    # Convert the frames into video
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    videoWriter = cv2.VideoWriter(
        './results/' + outname + '/overlay/video/movie.avi', fourcc, 40,
        (ny, nx))

    for iframe in tqdm(range(nframes)):
        frame = cv2.imread(DIR + 'img' + str(iframe) + '.jpg')
        videoWriter.write(frame)
    videoWriter.release()
    cv2.destroyAllWindows()
示例#3
0
def viewVideo():
    sideRight = Side("resources/video/record-2018-07-25-13-51-49_0_Trim.mp4",
                     "resources/calibration/11-09-0a-0f-05-09.yaml")
    # sideLeft = Side("resources/video/record-2018-07-25-13-51-49_1.mkv", "resources/calibration/04-1e-09-08-02-07.yaml")
    # sideFront = Side("resources/video/record-2018-07-25-13-51-49_2.mkv", "resources/calibration/11-14-0e-0f-05-09.yaml")
    # sideRear = Side("resources/video/record-2018-07-25-13-51-49_3.mkv", "resources/calibration/04-1e-1b-08-02-07.yaml")

    out = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'MJPG'), 30.0,
                          (1920, 1080))

    while sideRight.capture.isOpened():
        rat, imgRight = sideRight.getUndistortImage()
        if rat:
            # imgLeft = sideLeft.getUndistortImage()
            # imgFront = sideFront.getUndistortImage()
            # imgRear = sideRear.getUndistortImage()
            # dst = np.concatenate((img, dst1, dst2, dst3, dst4), 1)

            out.write(imgRight)

            # cv2.imshow("image", imgRight)
            if cv2.waitKey(0) & 0xFF == ord('q'):
                break
        else:
            break
    sideRight.capture.release()
    out.release()
    cv2.destroyAllWindows()
示例#4
0
def output_video(res_path, pname):
    """output videos from images
    Args:
        res_path: path to RESULTS/ which contains output images
        emf_name: folders contains h5 files, like b1_cyl_m/
    Return:
        None
    """
    outpath = res_path + pname + "/"
    outname = outpath + pname + ".mp4"
    filelist, filenum = input_file(outpath)
    for i in range(filenum):
        filelist[i] = outpath + "%s" % (str(filelist[i], "utf-8")).replace(
            "\n", "")
    test = cv2.imread(filelist[0])
    size = test.shape[:2]
    forcc = cv2.VideoWriter_fourcc(*'mp4v')
    videowrite = cv2.VideoWriter(outname, forcc, 10, (size[1], size[0]))
    img_array = []
    for filename in filelist:
        img = cv2.imread(filename)
        img_array.append(img)
    for i in range(filenum):
        videowrite.write(img_array[i])
    videowrite.release()
示例#5
0
def generateVideo(imageFrames):
    fourcc = cv2.VideoWriter_fourcc(*"MJPG")
    fps = 3
    videoWriter = cv2.VideoWriter("output.avi", fourcc, fps, (640, 480))
    for frame in imageFrames:
        videoWriter.write(frame)
    videoWriter.release()
def convertToVideo(pathIn, pathOut,itr,mDespList , fps, time):
    # converts images to video
    try:
        frame_array = []
        files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]
        # print(files)
        for i in range(len(files)):
            try:
                filename = pathIn+files[i]
                #print('.............'+filename)
                img=cv2.imread(filename)
                img = cv2.resize(img,(1920,1080)) #make it not stretch
                height, width, layers = img.shape
                size = (width,height)
                newsDescription = mDespList[itr]

                clipDur = int((len(newsDescription)/55)*11)
                
                for k in range (clipDur):
                    frame_array.append(img)
            
            except Exception as e:
                print(str(e))
    
        out = cv2.VideoWriter(pathOut, cv2.VideoWriter_fourcc(*'mp4v'), fps, size)
        for i in range(len(frame_array)):
            out.write(frame_array[i])
        out.release()

        editVideo(pathOut,itr,mDespList)
    except Exception as e:
        print(str(e))
示例#7
0
    def writeVideo(self, filename_output):
        temp_filename = filename_output.split('.')
        filename = temp_filename[0] + '_temp.' + temp_filename[1]

        if sys.platform == "win32":
            fourcc = cv2.VideoWriter_fourcc('R', 'G', 'B', 'A')     # 4-byte code used to specify the video codec.
        else:
            fourcc = cv2.VideoWriter_fourcc('M', 'P', 'N', 'G')     # 4-byte code used to specify the video codec.
            
        video_output = cv2.VideoWriter(filename, fourcc, self.fps, (self.width, self.height))
        for frame in self.frames:
            video_output.write(frame)
        video_output.release()

        try:
            cmd1 = self.ffmpeg_cmd + ' -i ' + filename + ' -i ' + self.filename + '_audio.wav -c:v copy -c:a aac ' + filename_output
            print(cmd1)
            subprocess.check_call(cmd1, shell=True)

            cmd2 = self.rm_cmd + ' ' + self.filename + '_audio.wav ' + filename
            print(cmd2)
            subprocess.call(cmd2, shell=True)

        except subprocess.CalledProcessError:
            
            cmd3 = self.rename_cmd + ' ' + filename + ' ' + filename_output
            print(cmd3)
            subprocess.call(cmd3, shell=True)


        return
示例#8
0
def writeVideo():
    cap = cv2.VideoCapture(0)

    cap.set(3, 320)
    cap.set(4, 240)
    now = datetime.datetime.now()
    fourcc = cv2.VideoWriter_fourcc(*'xvid')
    out = cv2.VideoWriter(
        'Encore/homework/Video/' + str(now.day) + '_' + str(now.hour) + '_' +
        str(now.minute) + '_' + str(now.second) + '.avi', fourcc, 25.0,
        (320, 240))

    nextTime = now + datetime.timedelta(seconds=3)
    while True:
        ret, frame = cap.read()

        if ret:
            out.write(frame)
            cv2.imshow('Video', frame)
            cv2.waitKey(1)
            if int((nextTime - datetime.datetime.now()).total_seconds()) == 0:
                break
        else:
            break
    cap.release()
    out.release()
    threading.Timer(3, writeVideo).start()
 def __init__(self,
              out_vid_name='',
              mov_detected_pixels_threshold=30,
              kernel_size=7,
              lot_of_noise_det=False,
              history=10,
              min_area=700):
     self.video_capture = cv2.VideoCapture(0)
     self.mog2 = cv2.createBackgroundSubtractorMOG2(history=history,
                                                    varThreshold=50,
                                                    detectShadows=True)
     self.knn = cv2.createBackgroundSubtractorKNN(history=10)
     self.current_frame = None
     self.previous_frame = None  # initially there is no previous frame
     self.kernel_size = kernel_size
     self.min_area = min_area
     self.lot_of_noise_det = lot_of_noise_det
     self.cap_frame_width = int(
         self.video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))
     self.cap_frame_height = int(
         self.video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
     codec = cv2.VideoWriter_fourcc(*'XVID')
     self.video_writer = cv2.VideoWriter(
         out_vid_name + '.avi', codec, 20.0,
         (self.cap_frame_width, self.cap_frame_height))
     self.mov_detected_pixels_threshold = mov_detected_pixels_threshold * WHITE_PIXEL_VALUE
示例#10
0
def writeVideo():
    if CaptureMode == False: return
    cap = cv2.VideoCapture(0)

    cap.set(3, 320)
    cap.set(4, 240)
    now = datetime.datetime.now()
    fourcc = cv2.VideoWriter_fourcc(*'xvid')
    out = cv2.VideoWriter(
        'Encore/homework/Video/' + str(now.day) + '_' + str(now.hour) + '_' +
        str(now.minute) + '_' + str(now.second) + '.avi', fourcc, 25.0,
        (320, 240))

    nextTime = now + datetime.timedelta(seconds=3)
    while True:
        ret, frame = cap.read()
        face = False
        if ret:
            out.write(frame)
            cv2.imshow('Video', frame)
            cv2.waitKey(1)
            if face == False: face = isFace(frame)
            if int((nextTime - datetime.datetime.now()).total_seconds()) == 0:
                break
        else:
            break
    cap.release()
    out.release()
    cv2.destroyAllWindows()
    if face == True:
        os.replace('')
        print(1)  # Face파일로 이동
    threading.Timer(3, writeVideo).start()
示例#11
0
def process_video(path):
    cap = cv2.VideoCapture(path)
    target = 20
    counter = 1

    writer = None
    (W, H) = (None, None)

    ans = []
    while True:
        print("counter" + str(counter))
        grabbed, frame = cap.read()

        if not grabbed:
            break

        if W is None or H is None:
            (H, W) = frame.shape[:2]

        if writer is None:
            fourcc = cv2.VideoWriter_fourcc(*"MJPG")
            writer = cv2.VideoWriter("src/testing_videos/output_video.avi",
                                     fourcc, 30, (W, H), True)

        if (counter % 10 == 0):
            write_frame(frame, writer)
        # lp, color = extract_attributes(frame)
        # if(lp is not None and color is not None):
        #     ans.append([lp, color])
        counter += 1

    return ans
示例#12
0
def construct_video_scene(
        args: argparse.Namespace,
        file_name: str) -> List[Dict[ID, detect.ObjectDetection]]:
    detection_pipeline = construct_detection_pipeline(args)
    out_file_name = file_name + '-out.mp4'

    # parse file and create cv2 parse object
    cap = cv2.VideoCapture(file_name)
    cap_framerate = cap.get(cv2.CAP_PROP_XI_FRAMERATE)
    cap_w = cap.get(cv2.CAP_PROP_XI_WIDTH)
    cap_h = cap.get(cv2.CAP_PROP_XI_HEIGHT)

    cap_framerate = 60
    cap_w = 1920
    cap_h = 1080

    # print(cap_framerate)
    #print((cap_w, cap_h))
    out = cv2.VideoWriter(
        out_file_name,
        cv2.VideoWriter_fourcc(*'DIVX'),
        cap_framerate,
        (cap_w, cap_h),
    )

    results = run_visualization(
        cap=cap,
        out=out,
        detection_pipeline=detection_pipeline,
    )

    cap.release()
    out.release()

    return results
示例#13
0
def read_video(video='video.MOV'):
    cap = cv2.VideoCapture(video)
    if (not cap.isOpened()): 
        print("Error opening video stream or file")

    frame_width = int(cap.get(3))
    frame_height = int(cap.get(4))
    out = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))

    while(cap.isOpened()):
        ret, frame = cap.read()
        if ret:
            # Display the resulting frame
            # cv2.imshow('', frame)
            frame = detect_emoji(frame)
            out.write(frame)

            # Press Q on keyboard to  exit
            if cv2.waitKey(25) & 0xFF == ord('q'):
                break
        else: break

    cap.release()
    out.release()
    cv2.destroyAllWindows()
示例#14
0
def record_stream_task():
    """
    Starts a recording
    """
    filepath = 'saved_demo.mp4'
    logging.info(f"Save location : {filepath}")

    try:
        vcap = cv2.VideoCapture(
            'http://192.168.43.1:4747/video?320x240')  # 'demo.mp4'
        # fourcc = cv2.VideoWriter_fourcc(*'MP4V')

        fw = int(vcap.get(3))
        fh = int(vcap.get(4))

        print(fw, fh)

        out = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc(*'MP4V'),
                              20.0, (fw, fh))

        print("Starting writer")

        while vcap.isOpened():
            flag, frame = vcap.read()
            if flag:
                out.write(frame)
                cv2.imshow('Frame', frame)
                if cv2.waitKey(1) & 0xFF == ord('s'):
                    break
            else:
                break

    except:
        logging.error("SOMETHING WENT WRONG")
        exit()
def main():
    debug = True
    begin_session_allocate_memory()
    # model = tf.keras.models.load_model("emotion_model_v1.0_3cnn_2dns_input64x64.model")
    # model = tf.keras.models.load_model("faceNet\\3cnn_2dnn_no_regularization")
    model = tf.keras.models.load_model("faceNet\\xNet")

    width, height = pyautogui.size()
    path = "output/"
    out = None
    if debug:
        fourcc = cv2.VideoWriter_fourcc(*"XVID")
        screen_size = (width, height)
        out = cv2.VideoWriter(path+"video/output.avi", fourcc, 20.0, (screen_size))
    Path(path).mkdir(exist_ok=True)
    
    classifier = Faces(width, height, model, path, out)
    try:
        classifier.find_face()
    except KeyboardInterrupt:
        if out:
            out.release()
        cv2.destroyAllWindows()  
        tf.keras.backend.clear_session()
        print("Ending session")
    def SaveFramesToVideo(frames,
                          outputPath,
                          fourcc=cv2.VideoWriter_fourcc(*'XVID'),
                          fps=20.0):
        """Lê um conjunto de frames em uma pasta

        Parameters:
            frames (Array): Array de Frames do Video
            outputPath (String): Caminho do Video
            fourcc (Object): Codec do Video
            fps (Float): Frames por Segundo

        """
        if (len(frames) == 0): return

        size = len(frames)

        width = frames[0].shape[1]
        height = frames[0].shape[0]
        dsize = (width, height)

        loop = tqdm(total=size, position=0, leave=False)
        out = cv2.VideoWriter(outputPath, fourcc, fps, dsize)

        for frame in frames:
            out.write(frame)
            loop.set_description("Salvando Frame...")
            loop.update(1)

        loop.close()
        out.release()
def generate_cropped_video(frames):
    MAX_EXTRACT_COUNT = 500
    extract_count = 1

    video_dir = get_video_dir()

    frame_index = 0

    for file in os.listdir(video_dir):
        video_path = video_dir + '\\' + file

        cap = cv2.VideoCapture(video_path)

        obj = frames[frame_index]
        x1 = obj.topLeft[0]
        y1 = obj.topLeft[1]
        x2 = obj.bottomRight[0]
        y2 = obj.bottomRight[1]

        video_output = get_opencv_dir() + '\\' + file
        fps = cap.get(cv2.CAP_PROP_FPS)
        fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
        frame_width = x2 - x1
        frame_height = y2 - y1

        out = cv2.VideoWriter(video_output, fourcc, fps,
                              (frame_width, frame_height))

        print(f'\nEXTRACTING {extract_count} of {MAX_EXTRACT_COUNT}')
        print(f'Writing {file} . . .')

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

            if ret:
                # Region of interest
                roi = frame[y1:y2, x1:x2]

                out.write(roi)

                # cv2.imshow('frame', roi)

                # if cv2.waitKey(1) & 0xFF == ord('q'):
                #     break

            else:
                break

        # When everything is done, release the video capture and video write objects
        cap.release()
        out.release()

        # Close all the frames
        cv2.destroyAllWindows()

        frame_index += 1
        extract_count += 1

    print('EXTRACTING FINISHED')
示例#18
0
 def __init__(self, videofile='record.avi'):
     threading.Thread.__init__(self)
     self.bRecord = True
     self.video = cv2.VideoWriter(
         videofile,
         cv2.VideoWriter_fourcc(*'XVID'),
         32,  # (1919, 1079))
         ImageGrab.grab(bbox=(0, 0, 1920, 1080)).size)  # 帧率为32,可以调节
def main(inputPath, outputPath, palettePath):
    DIR_PATH = os.path.dirname(os.path.abspath(__file__))

    #Load Palette
    paletteNameList = glob.glob(palettePath + "*.png")
    paletteNameList = sorted(paletteNameList)

    palette = []
    for imgName in paletteNameList:
        print(imgName)
        img = cv2.imread(imgName)
        palette.append(img)

    paletteSize = len(palette)

    # Create a VideoCapture object
    cap = cv2.VideoCapture(inputPath)

    # Check if camera opened successfully
    if (cap.isOpened() == False):
        print("Unable to read camera feed")

    # Default resolutions of the frame are obtained.The default resolutions are system dependent.
    # We convert the resolutions from float to integer.
    frame_width = int(cap.get(3))
    frame_height = int(cap.get(4))

    # Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
    out = cv2.VideoWriter(outputPath,
                          cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 30,
                          (frame_width, frame_height))

    cpt = 0
    while (True):
        print(cpt / 30)
        ret, frame = cap.read()

        if ret == True:
            ref = interpolePalette(palette, cpt / 100)
            result = transfert(frame, ref)

            out.write(result)
            #cv2.imshow('frame',result)
            # Press Q on keyboard to stop recording
            #if cv2.waitKey(1) & 0xFF == ord('q'):
            #    break
        # Break the loop
        else:
            break

        cpt += 1

    # When everything done, release the video capture and video write objects
    cap.release()
    out.release()

    # Closes all the frames
    cv2.destroyAllWindows()
示例#20
0
def capture(path, choice, margin, text):
    video = cv2.VideoCapture(path)  # video object
    countFrame = 0
    img_array = []  # store all the watermaked frames
    progress_bar = tqdm(unit=" Frames Processed", unit_scale=True)
    while video.isOpened():
        sucess, frame = video.read()
        if sucess == False:
            break
        cv2.imwrite("frame" + str(countFrame) + ".jpg", frame)
        image = Image.open("frame" + str(countFrame) + ".jpg")
        width, height = image.size
        size = (width, height)
        draw = ImageDraw.Draw(image)  # drawing object
        font = ImageFont.truetype("arial.ttf", 36)
        textwidth, textheight = draw.textsize(text, font)
        if choice == "C":
            x = (width - textwidth) / 2
            y = (height - textheight) / 2
        elif choice == "RB":
            x = width - textwidth - margin
            y = height - textheight - margin
        elif choice == "LT":
            x = margin
            y = margin
        elif choice == "LB":
            x = margin
            y = height - textheight - margin
        elif choice == "RT":
            x = width - textwidth - margin
            y = margin
        else:
            print("Invalid choice!")
            break

        draw.text((x, y), text, font=font)
        image.save("frame converted" + str(countFrame) + ".jpg")
        img = cv2.imread("frame converted" + str(countFrame) + ".jpg")
        img_array.append(img)
        os.remove("frame" + str(countFrame) + ".jpg")
        os.remove("frame converted" + str(countFrame) + ".jpg")
        progress_bar.update()
        countFrame += 1

    video.release()
    video_write = cv2.VideoWriter("output.avi",
                                  cv2.VideoWriter_fourcc(*"DIVX"), 30, size)
    for i in range(len(img_array)):
        video_write.write(img_array[i])
    video_write.release()

    my_clip = mpe.VideoFileClip("output.avi")
    audio_background = mpe.VideoFileClip(path).audio
    final_clip = my_clip.set_audio(audio_background)
    final_clip.write_videofile("output.mp4")

    os.remove("output.avi")
示例#21
0
    def run_on_video(self,
                     side=None,
                     skeleton=1,
                     mode=None,
                     joints=True,
                     threshold=.5,
                     color_mode=None,
                     draw_invisible=False,
                     save_output=False,
                     save_path=None,
                     debug_params=None):
        if self.path_to_video is None:
            return

        output_file = None

        with self:
            if save_output:
                if save_path is None:
                    output_filename = os.path.join(
                        self.basename.split('.')[0] + "_out.mp4")
                else:
                    output_filename = save_path

                output_file = cv2.VideoWriter(
                    filename=output_filename,
                    fourcc=cv2.VideoWriter_fourcc(*"mp4v"),
                    fps=float(self.frames_per_second),
                    frameSize=(self.width, self.height),
                    isColor=True,
                )

            frame_gen = self._frame_from_video(self.video)
            for frame in frame_gen:
                keypoints = self.get_keypoints(frame)
                frame = visualize_keypoints_mp(keypoints,
                                               frame,
                                               skeleton=skeleton,
                                               side=side,
                                               mode=mode,
                                               scale=self.scale,
                                               threshold=threshold,
                                               color_mode=color_mode,
                                               draw_invisible=draw_invisible,
                                               joints=joints,
                                               dict_is_updated=False)
                if save_output:
                    output_file.write(frame)

                yield frame, keypoints

            self.video.release()

            if save_output:
                output_file.release()
            else:
                cv2.destroyAllWindows()
示例#22
0
def __main__():
    

    model = videoDetectTest.loadModel()

    videoFile = input("Vul hier de bestandsnaam van de te detecteren video in (zorg dat ie in dezelfde map zit!): ")
    
    if(videoFile == '0'):
        videoFile = 0
    
    video_capture = cv2.VideoCapture(videoFile)

    fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
    vidWidth = video_capture.get(3)
    vidHeight = video_capture.get(4)
    fps = video_capture.get(5)
    print(vidWidth, vidHeight, fps)

    if(videoFile != 0):
        out = cv2.VideoWriter(videoFile[:-4] + '_detected' + videoFile[-4:],
                            fourcc,
                            fps,
                            (int(vidWidth), int(vidHeight)))

    videoDetectTest.downloadCheck()
    videoDetectTest.yoloModelCheck()

    frameNo = 1
    
    if(videoFile != 0):
        totalFrames = int(cv2.VideoCapture.get(video_capture, int(cv2.CAP_PROP_FRAME_COUNT)))

        print(totalFrames)

    while(True):

        ret, frame = video_capture.read()

        imageFinal = videoDetectTest.__main__(model, frame)

        cv2.imshow('Video', imageFinal)
        
        if(videoFile != 0):
            out.write(cv2.resize(imageFinal, (int(vidWidth), int(vidHeight))))

            print("Frame " + str(frameNo) + " van de " + str(totalFrames) + " frames in de video is opgeslagen!")
        frameNo += 1

        if cv2.waitKey(1) & 0xFF == ord('Q'):
            print("Gestopt!")

            break
    
    video_capture.release()
    cv2.destroyAllWindows()

    out.release()
示例#23
0
def getVideoInfo(video_path, pose_model, yolo, output_path=""):
    from cv2 import cv2
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise IOError("Couldn't open webcam or video")
    fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))  # 获取原始视频的信息
    fps = cap.get(cv2.CAP_PROP_FPS)
    size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
            int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    isOutput = True if output_path != "" else False  # 如果设置了视频保存路径,则保存视频
    if isOutput:
        print("[INFO] video TYPE:", type(output_path), type(fourcc), type(fps),
              type(size))
        out = cv2.VideoWriter(output_path, fourcc, fps,
                              size)  # 根据原视频设置 保存视频的路径、大小、帧数
    accum_time = 0
    curr_fps = 0
    fps = "FPS: ??"
    prev_time = time.time()
    while True:
        ret, frame = cap.read()

        if ret:
            info, lineimage = getImgInfo(frame, pose_model, yolo)  # 每一帧检测
            curr_time = time.time()
            exec_time = curr_time - prev_time
            prev_time = curr_time
            accum_time = accum_time + exec_time
            curr_fps = curr_fps + 1
            if accum_time > 1:
                accum_time = accum_time - 1
                fps = "FPS: " + str(curr_fps)
                curr_fps = 0
            cv2.putText(lineimage,
                        text=fps,
                        org=(3, 15),
                        fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                        fontScale=0.50,
                        color=(255, 0, 0),
                        thickness=2)
            cv2.putText(lineimage,
                        "q-'quit'",
                        org=(3, 45),
                        fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                        fontScale=0.50,
                        color=(0, 255, 0),
                        thickness=2)  # 标注字体
            cv2.namedWindow("result", cv2.WINDOW_NORMAL)
            cv2.imshow("result", lineimage)
            if isOutput:
                out.write(lineimage)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cap.release()
    out.release()
    cv2.destroyAllWindows()
    def save_frames(self, name, matrix, ratio_width):
        """
        Функция сохраняет видеозапись после обработки
        """
        fps = FPS().start()
        centroid_tracker = CentroidTracker(max_disappeared=100,
                                           max_distance=200)
        fourcc = cv2.VideoWriter_fourcc(
            *'mp4v'
        )  # Не лучший вариант, но на выше стоящие кодеки вызывается ошибка
        if not self.cap.isOpened():
            print("[INFO] failed to process video")
            raise
        ret, frame = self.cap.read()
        filename = f'{name}.mp4'
        folder = app.config['UPLOAD_FOLDER'] + '/' + filename
        filename_csv = app.config['UPLOAD_FOLDER'] + f'/CSV_{name}.csv'

        out_video = cv2.VideoWriter(folder, fourcc, self.skip_frames,
                                    (frame.shape[1], frame.shape[0]))
        with open(filename_csv, mode="w", encoding='utf-8') as file:
            file.write("timestamp;ID;speed\r\n")
        print("[INFO] video quality: {} {}".format(frame.shape[1],
                                                   frame.shape[0]))
        trackers = list()
        while self.cap.isOpened():
            ret, frame = self.cap.read()
            if ret:
                rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                rect = list()
                if self.frame_count % self.skip_frames < 1:
                    trackers = list()
                    width, height, out = self.config(frame)
                    self.search_people(width, height, out, rgb, trackers)
                else:
                    self.status_tracking(rect, rgb, frame, trackers)
                objects = centroid_tracker.update(rect)
                self.object_and_speed(filename_csv, objects, frame, matrix,
                                      ratio_width)

                info = [("Number of tracked objects", len(objects)),
                        ("Recognition percentage", self.percent),
                        ("Recognition object", self.class_name[15])]
                self.statistics_output(info, frame)
                self.frame_count += 1

                fps.update()
                out_video.write(frame)
            else:
                break
        fps.stop()
        print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
        print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
        self.cap.release()
        out_video.release()
        return str(filename)
示例#25
0
    def __readVideo__(self,
                      video: cv2.VideoCapture,
                      cameraMapping: CameraMapping,
                      output_url: str = None,
                      conf_threshold: float = 0.5,
                      display: bool = False,
                      draw: bool = True):
        # Initialize arguments
        scale = 0.00392
        nms_threshold = 0.4

        # Read the first frame
        response, frame = video.read()
        frame_number = 0
        car_counter = VehicleCounter(frame.shape[:2],
                                     video.get(cv2.CAP_PROP_FPS),
                                     cameraMapping)

        # Create output video
        if output_url:
            fourcc = cv2.VideoWriter_fourcc(*'mp4v')
            out = cv2.VideoWriter(output_url, fourcc, 15,
                                  (frame.shape[1], frame.shape[0]))

        # Loop while there is a frame
        while response:

            # Get detections for the frame
            matches, confidences, class_ids = self.get_img_detections(
                frame,
                conf_threshold=conf_threshold,
                nms_threshold=nms_threshold,
                scale=scale)

            # Update the car counter
            car_counter.update_count(matches.copy(),
                                     frame_number,
                                     frame,
                                     draw=draw)

            if draw:
                for contour, confidence, class_id in zip(
                        matches, confidences, class_ids):
                    self.__draw_bounding_box__(frame, class_id, confidence,
                                               contour)
            if display:
                self.__display_img__(frame, wait=0, destroyAll=True)
            if output_url:
                out.write(frame)

            frame_number += 1
            response, frame = video.read()

        cv2.destroyAllWindows()
        if output_url:
            out.release()
示例#26
0
 def send_video_to_recipients(self, frames):
     self.bot.sendMessage(self.config['chat_id'], 'Motion detected!')
     name = os.path.join(gettempdir(), f'{random()}.mp4')
     height, width, _ = frames[0].shape
     vid = cv2.VideoWriter(name, cv2.VideoWriter_fourcc(*'mp4v'), 20.0,
                           (width, height))
     for frame in frames:
         vid.write(frame)
     vid.release()
     self.bot.sendVideo(self.config['chat_id'], open(name, 'rb'))
def save_webcam(outPath, fps, mirror=False):
    # Capturing video from webcam:
    cap = cv.VideoCapture(0)
    currentFrame = 0
    # Get current width of frame
    width = cap.get(cv.CAP_PROP_FRAME_WIDTH)  # float
    # Get current height of frame
    height = cap.get(cv.CAP_PROP_FRAME_HEIGHT)  # float
    # Define the codec and create VideoWriter object
    fourcc = cv.VideoWriter_fourcc(*"XVID")
    out = cv.VideoWriter(outPath, fourcc, fps, (int(width), int(height)))

    prev_ret, prev_frame = cap.read()
    if prev_ret:
        prev_frame = cv.flip(prev_frame, 1)

    while cap.isOpened():
        # Capture frame-by-frame
        ret, frame = cap.read()

        if ret:
            if mirror:
                # Mirror the output video frame
                frame = cv.flip(frame, 1)
            # Saves for video
            out.write(frame)

            # Calculate the distance of the 2 pictures
            diff = np.sum(
                (prev_frame.astype("float") - frame.astype("float")) *
                (prev_frame.astype("float") - frame.astype("float")))
            diff = diff / (prev_frame.shape[0] * frame.shape[1])

            if diff > threshold:
                print(
                    "/!\ Attention /!\ Quelqu'un s'est introduit dans la matrice !"
                    + diff.__str__())

            prev_frame = frame

            # Display the resulting frame
            cv.imshow('frame', frame)
        else:
            break

        if cv.waitKey(1) & 0xFF == ord('q'):  # if 'q' is pressed then quit
            break

        # To stop duplicate images
        currentFrame += 1

    # When everything done, release the capture
    cap.release()
    out.release()
    cv.destroyAllWindows()
示例#28
0
def video_writer(input_path: str,
                 output_path: str,
                 outputDict: dict,
                 output_frame_resolution=(854, 480)):

    cap = cv.VideoCapture(input_path)
    frames_processed = 0

    fourcc = cv.VideoWriter_fourcc(*'MJPG')
    prediction_out = cv.VideoWriter(output_path, fourcc, 30,
                                    output_frame_resolution)

    with tqdm(total=float("inf")) as pbar:
        while cap.isOpened():
            try:
                ret, frame = cap.read()

                # Check for proper read
                if not ret:
                    break

                # Process the frame
                frame = cv.resize(frame,
                                  output_frame_resolution,
                                  interpolation=cv.INTER_CUBIC)

                # frames processed
                frames_processed += 1
                out = outputDict.get(frames_processed, -1)
                if out != -1:
                    x, y, width, height = out["bounding_box"]
                    distance = out["distance"]
                    cv.rectangle(frame, (x, y), (x + width, y + height),
                                 (36, 255, 12), 2)
                    cv.putText(frame, f'Subject-{distance:.4f}', (x, y - 10),
                               cv.FONT_HERSHEY_PLAIN, 1.0, (36, 255, 12), 2)
                prediction_out.write(frame)
                cv.imshow('frame', frame)

                pbar.set_postfix_str(f"Frames Processed: {frames_processed}")
                pbar.update(1)

                # Break condition
                if cv.waitKey(1) & 0xFF == ord('q'):
                    break

            except Exception as err:
                print(f"[ERROR]: {err}")
                print(f"[ERROR]: {traceback.print_exc()}")
                return False

    cap.release()
    prediction_out.release()
    cv.destroyAllWindows()
    return True
示例#29
0
def store_video(frames, path):
    height, width, _ = frames[0].shape
    size = (width, height)
    out = cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*'MJPG'), 30, size)
    count = 0
    for frame in frames:
        print(f'Appending frame: {count}.jpg....')
        out.write(frame)
        count += 1

    out.release()
示例#30
0
    def Start(self, fileName, fps, width, height, fourcc):
        self.fileName = fileName
        self.writing = True
        with self.queue.mutex:
            self.queue.queue.clear()

        self.videoWriter = cv2.VideoWriter(fileName,
                                           cv2.VideoWriter_fourcc(*fourcc),
                                           fps, (width, height))
        self.writeThread = threading.Thread(target=self.Run)
        self.writeThread.start()