Python cv2.selectROI() Examples

The following are 8 code examples of cv2.selectROI(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: cvutils.py    From 1ZLAB_PyEspCar with GNU General Public License v3.0 7 votes vote down vote up
def select_roi(target):
    # 创建一个窗口
    cv2.namedWindow("image", flags= cv2.WINDOW_NORMAL | cv2.WINDOW_FREERATIO)
    cv2.imshow("image", target)
    # 是否显示网格 
    showCrosshair = True

    # 如果为Ture的话 , 则鼠标的其实位置就作为了roi的中心
    # False: 从左上角到右下角选中区域
    fromCenter = False
    # Select ROI
    rect = cv2.selectROI("image", target, showCrosshair, fromCenter)

    print("选中矩形区域")
    (x, y, w, h) = rect

    # Crop image
    roi = target[y : y+h, x:x+w]
    
    return rect, roi 
Example #2
Source File: track_logger.py    From Multi-Camera-Object-Tracking with GNU General Public License v3.0 6 votes vote down vote up
def write_to_trackfile(track_info):
    # st = time.time()
    with open(WORK_DIR + "/METADATA/" + "trackfile.txt", "a+") as f:
        for item in track_info:
            f.write(str(item) + "\n")
            # print(str(item) + "\n")
        f.close()
    # et = time.time()
    # print ("write time:", et - st)
    # sys.exit()
    
#uncomment to use as stand-alone file
# start_frame = 8*3
# vid = VIDEO_PATH + "/cam_8.avi"
# cap = cv2.VideoCapture(vid)
# cap.set(cv2.CAP_PROP_FPS, 8)
# cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
# ok, frame = cap.read()
# bbox = selectROI(frame)
# track(0,cap,bbox,2)


# cam_id, cap, bbox, data_inc 
Example #3
Source File: tkinter_functions.py    From simba with GNU Lesser General Public License v3.0 5 votes vote down vote up
def youOnlyCropOnce(inputdir,outputdir):
    filesFound=[]
    ########### FIND FILES ###########
    for i in os.listdir(inputdir):
        if i.endswith(('.avi', '.mp4', '.mov', 'flv')):
            filesFound.append(os.path.join(inputdir,i))
    filenames=filesFound[0]
    #extract one frame
    currentDir = str(os.path.dirname(filenames))
    videoName = str(os.path.basename(filenames))
    os.chdir(currentDir)
    cap = cv2.VideoCapture(videoName)
    cap.set(1, 0)
    ret, frame = cap.read()
    fileName = str(0) + str('.bmp')
    filePath = os.path.join(currentDir, fileName)
    cv2.imwrite(filePath, frame)
    #find ROI

    img = cv2.imread(filePath)
    cv2.namedWindow('Select ROI', cv2.WINDOW_NORMAL)
    ROI = cv2.selectROI("Select ROI", img)
    width = abs(ROI[0] - (ROI[2] + ROI[0]))
    height = abs(ROI[2] - (ROI[3] + ROI[2]))
    topLeftX = ROI[0]
    topLeftY = ROI[1]
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    for i in filesFound:
        #crop video with ffmpeg
        fileOut, fileType = i.split(".", 2)
        fileOutName = outputdir + '\\'+ os.path.basename(str(fileOut)) + str('_cropped.')+ str(fileType)
        command = str('ffmpeg -i ') +'"'+ str(i) +'"'+ str(' -vf ') + str('"crop=') + str(width) + ':' + str(
            height) + ':' + str(topLeftX) + ':' + str(topLeftY) + '" ' + str('-c:v libx264 -crf 21 -c:a copy ') +'"'+ str(
            fileOutName)+'"'
        total = width + height + topLeftX + topLeftY

        file = pathlib.Path(fileOutName)
        if file.exists():
            print(os.path.basename(fileOutName), 'already exist')
        else:
            if width==0 and height ==0:
                print('Video not cropped')
            elif total != 0:
                print('Cropping video...')
                print(command)
                subprocess.call(command, shell=True)
            elif total ==0:
                print('Video not cropped')

    os.remove(filePath)
    print('Process completed.') 
Example #4
Source File: demo.py    From SiamFC-tf with MIT License 5 votes vote down vote up
def main():
    # debug = 0 , no log will produce
    # debug = 1 , will produce log file
    tracker = SiameseTracker(debug=0)
    time_per_frame = 0

    if len(sys.argv) <= 1:
        print('[ERROR]: File path error!')
        return

    if sys.argv[1] == "cam":
        cap = cv2.VideoCapture(0)
    else:
        cap = cv2.VideoCapture(sys.argv[1])

    while True:
        # Capture frame-by-frame
        ret, frame = cap.read()
        frame = preprocess(frame)
        cv2.imshow('frame', postprocess(frame))
        if cv2.waitKey(1500) & 0xFF == ord('o'):
            break

    # select ROI and initialize the model
    r = cv2.selectROI(postprocess(frame))
    cv2.destroyWindow("ROI selector")
    print('ROI:', r)
    tracker.set_first_frame(frame, r)

    while True:
        ret, frame = cap.read()
        frame = preprocess(frame)
        start_time = datetime.datetime.now()
        reported_bbox = tracker.track(frame)
        end_time = datetime.datetime.now()

        # Display the resulting frame
        # print(reported_bbox)
        cv2.rectangle(frame, (int(reported_bbox[0]), int(reported_bbox[1])),
                      (
                          int(reported_bbox[0]) + int(reported_bbox[2]),
                          int(reported_bbox[1]) + int(reported_bbox[3])),
                      (0, 0, 255), 2)

        duration = end_time - start_time
        time_per_frame = 0.9 * time_per_frame + 0.1 * duration.microseconds
        cv2.putText(frame, 'FPS ' + str(round(1e6 / time_per_frame, 1)),
                    (30, 50), 0, 1, (0, 0, 255), 3)

        cv2.imshow('frame', postprocess(frame))

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

    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows() 
Example #5
Source File: tkinter_functions.py    From simba with GNU Lesser General Public License v3.0 4 votes vote down vote up
def cropvid(filenames):
    if filenames:

        #extract one frame
        currentDir = str(os.path.dirname(filenames))
        videoName = str(os.path.basename(filenames))
        os.chdir(currentDir)
        cap = cv2.VideoCapture(videoName)
        cap.set(1, 0)
        ret, frame = cap.read()
        fileName = str(0) + str('.bmp')
        filePath = os.path.join(currentDir, fileName)
        cv2.imwrite(filePath, frame)
        #find ROI

        img = cv2.imread(filePath)
        cv2.namedWindow('Select ROI', cv2.WINDOW_NORMAL)
        ROI = cv2.selectROI("Select ROI", img)
        width = abs(ROI[0] - (ROI[2] + ROI[0]))
        height = abs(ROI[2] - (ROI[3] + ROI[2]))
        topLeftX = ROI[0]
        topLeftY = ROI[1]
        cv2.waitKey(0)
        cv2.destroyAllWindows()

        #crop video with ffmpeg
        fileOut, fileType = videoName.split(".", 2)
        fileOutName = str(fileOut) + str('_cropped.mp4')
        command = str('ffmpeg -i ') +'"'+ str(videoName) +'"'+ str(' -vf ') + str('"crop=') + str(width) + ':' + str(
            height) + ':' + str(topLeftX) + ':' + str(topLeftY) + '" ' + str('-c:v libx264 -crf 21 -c:a copy ') +'"'+ str(
            fileOutName)+'"'
        total = width + height + topLeftX + topLeftY

        file = pathlib.Path(fileOutName)
        if file.exists():
            print(os.path.basename(fileOutName), 'already exist')
        else:
            if width==0 and height ==0:
                print('Video not cropped')
            elif total != 0:
                print('Cropping video...')
                print(command)
                subprocess.call(command, shell=True)
                os.remove(filePath)
                print('Cropped video saved!')
                return fileOutName
            elif total ==0:
                print('Video not cropped')

        os.remove(filePath)

    else:
        print('Please select a video to crop') 
Example #6
Source File: process_videos_automation.py    From simba with GNU Lesser General Public License v3.0 4 votes vote down vote up
def cropvid_auto(filenames,outputdir):
    global width,height

    #extract one frame
    currentDir = str(os.path.dirname(filenames))
    videoName = str(os.path.basename(filenames))
    os.chdir(currentDir)
    cap = cv2.VideoCapture(videoName)
    cap.set(1, 0)
    ret, frame = cap.read()
    fileName = str(0) + str('.bmp')
    filePath = os.path.join(currentDir, fileName)
    cv2.imwrite(filePath, frame)

    #find ROI

    img = cv2.imread(filePath)
    cv2.namedWindow('Select ROI', cv2.WINDOW_NORMAL)
    ROI = cv2.selectROI("Select ROI", img)
    width = abs(ROI[0] - (ROI[2] + ROI[0]))
    height = abs(ROI[2] - (ROI[3] + ROI[2]))
    topLeftX = ROI[0]
    topLeftY = ROI[1]
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    #crop video with ffmpeg
    fileOut, fileType = videoName.split(".", 2)
    fileOutName = str(fileOut) + str('_cropped.mp4')



    total = width+height+topLeftX +topLeftY

    if total != 0:
        command = (str('ffmpeg -y -i ') + str(outputdir) + '\\' + str(videoName) + str(' -vf ') + str('"crop=') + str(width) + ':' + str(height) + ':' + str(topLeftX) + ':' + str(topLeftY) + '" ' + str('-c:v libx264 -c:a copy ') + str(os.path.join(outputdir, fileOutName)) + '\n'
            'move \"' + str(outputdir) + '\\' + videoName + '\" \"' + (outputdir) + '\\' + 'tmp\"' + '\n'
             'copy \"' + str(outputdir) + '\\' + os.path.basename(fileOutName) + '\" \"' + (outputdir) + '\\' + 'tmp\"' + '\n'
            'rename \"' + os.path.join(str(outputdir), os.path.basename(fileOutName)) + '\" \"' + os.path.basename(videoName) + '\"')
        print(videoName,'added into the crop video queue.')
        os.remove(filePath)
    elif total == 0:
        command = []
        print('nothing added to the script as no coordinates was selected')

    if os.path.exists(filePath):
        os.remove(filePath)
    return command 
Example #7
Source File: process_videos_automation.py    From simba with GNU Lesser General Public License v3.0 4 votes vote down vote up
def cropvid_queue(filenames,outputdir):
    global width,height
    #extract one frame
    currentDir = str(os.path.dirname(filenames))
    videoName = str(os.path.basename(filenames))
    os.chdir(currentDir)
    cap = cv2.VideoCapture(videoName)
    cap.set(1, 0)
    ret, frame = cap.read()
    fileName = str(0) + str('.bmp')
    filePath = os.path.join(currentDir, fileName)
    cv2.imwrite(filePath, frame)

    #find ROI

    img = cv2.imread(filePath)
    cv2.namedWindow('Select ROI', cv2.WINDOW_NORMAL)
    ROI = cv2.selectROI("Select ROI", img)
    width = abs(ROI[0] - (ROI[2] + ROI[0]))
    height = abs(ROI[2] - (ROI[3] + ROI[2]))
    topLeftX = ROI[0]
    topLeftY = ROI[1]
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    #crop video with ffmpeg
    fileOut, fileType = videoName.split(".", 2)
    fileOutName = str(fileOut) + str('_cropped.mp4')

    total = width+height+topLeftX +topLeftY

    if total != 0:
        command = (str('ffmpeg -y -i ')+ '"' + str(outputdir) + '\\' + str(videoName)+ '"' + str(' -vf ') + str('"crop=') + str(width) + ':' + str(height) + ':' + str(topLeftX) + ':' + str(topLeftY) + '" ' + str('-c:v libx264 -c:a copy ') + '"'+ str(os.path.join(outputdir, fileOutName))+ '"' + '\n'
            'move \"' + str(outputdir) + '\\' + videoName + '\" \"' + (outputdir) + '\\' + 'tmp\"' + '\n'
             'copy \"' + str(outputdir) + '\\' + os.path.basename(fileOutName) + '\" \"' + (outputdir) + '\\' + 'tmp\"' + '\n'
            'rename \"' + os.path.join(str(outputdir), os.path.basename(fileOutName)) + '\" \"' + os.path.basename(videoName) + '\"')
        print(videoName, 'added into the crop video queue.')
        os.remove(filePath)
        return command
    else:
        print('nothing added to the script as no coordinates was selected')
        pass
    if os.path.exists(filePath):
        os.remove(filePath) 
Example #8
Source File: demo.py    From pysot with Apache License 2.0 4 votes vote down vote up
def main():
    # load config
    cfg.merge_from_file(args.config)
    cfg.CUDA = torch.cuda.is_available() and cfg.CUDA
    device = torch.device('cuda' if cfg.CUDA else 'cpu')

    # create model
    model = ModelBuilder()

    # load model
    model.load_state_dict(torch.load(args.snapshot,
        map_location=lambda storage, loc: storage.cpu()))
    model.eval().to(device)

    # build tracker
    tracker = build_tracker(model)

    first_frame = True
    if args.video_name:
        video_name = args.video_name.split('/')[-1].split('.')[0]
    else:
        video_name = 'webcam'
    cv2.namedWindow(video_name, cv2.WND_PROP_FULLSCREEN)
    for frame in get_frames(args.video_name):
        if first_frame:
            try:
                init_rect = cv2.selectROI(video_name, frame, False, False)
            except:
                exit()
            tracker.init(frame, init_rect)
            first_frame = False
        else:
            outputs = tracker.track(frame)
            if 'polygon' in outputs:
                polygon = np.array(outputs['polygon']).astype(np.int32)
                cv2.polylines(frame, [polygon.reshape((-1, 1, 2))],
                              True, (0, 255, 0), 3)
                mask = ((outputs['mask'] > cfg.TRACK.MASK_THERSHOLD) * 255)
                mask = mask.astype(np.uint8)
                mask = np.stack([mask, mask*255, mask]).transpose(1, 2, 0)
                frame = cv2.addWeighted(frame, 0.77, mask, 0.23, -1)
            else:
                bbox = list(map(int, outputs['bbox']))
                cv2.rectangle(frame, (bbox[0], bbox[1]),
                              (bbox[0]+bbox[2], bbox[1]+bbox[3]),
                              (0, 255, 0), 3)
            cv2.imshow(video_name, frame)
            cv2.waitKey(40)