本文整理匯總了Python中cv2.selectROI方法的典型用法代碼示例。如果您正苦於以下問題:Python cv2.selectROI方法的具體用法?Python cv2.selectROI怎麽用?Python cv2.selectROI使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cv2
的用法示例。
在下文中一共展示了cv2.selectROI方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: select_roi
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import selectROI [as 別名]
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
示例2: write_to_trackfile
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import selectROI [as 別名]
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
示例3: cropvid
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import selectROI [as 別名]
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')
示例4: youOnlyCropOnce
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import selectROI [as 別名]
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.')
示例5: cropvid_auto
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import selectROI [as 別名]
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
示例6: cropvid_queue
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import selectROI [as 別名]
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)
示例7: main
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import selectROI [as 別名]
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()
示例8: main
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import selectROI [as 別名]
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)