How to use __capture method in ATX

Best Python code snippet using ATX

CameraCapture.py

Source:CameraCapture.py Github

copy

Full Screen

1#!/usr/bin/python2.72# -*- coding:utf-8 -*-3__author__ = 'lh'4__version__ = 1.05__date__ = 22/12/20156import sys7sys.path.append("../../")8import cv29try:10 import cv2.cv as cv11 OPENCV_VERSION = '2.0+'12except:13 print 'can not import cv2.cv'14 print 'cv2.cv is removed in opencv3.0+'15 OPENCV_VERSION = '3.0+'16import numpy as np17import threading18import time19import logging20class OpencvImportError(Exception):21 pass22class CameraSettingError(Exception):23 pass24class KeyBoardQuitSignal(Exception):25 pass26class CameraCapture(object):27 Logger = logging.getLogger('Camera')28 if '2.0+' == OPENCV_VERSION:29 FRAME_WIDTH = cv.CV_CAP_PROP_FRAME_WIDTH30 FRAME_HEIGHT = cv.CV_CAP_PROP_FRAME_HEIGHT31 POS_MSEC = cv.CV_CAP_PROP_POS_MSEC32 POS_FRAMES = cv.CV_CAP_PROP_POS_FRAMES33 AVI_RATIO = cv.CV_CAP_PROP_POS_AVI_RATIO34 FPS = cv.CV_CAP_PROP_FPS35 FOURCC = cv.CV_CAP_PROP_FOURCC36 FRAME_COUNT = cv.CV_CAP_PROP_FRAME_COUNT37 FORMAT = cv.CV_CAP_PROP_FORMAT38 MODE = cv.CV_CAP_PROP_MODE39 BRIGHTNESS = cv.CV_CAP_PROP_BRIGHTNESS40 CONTRAST = cv.CV_CAP_PROP_CONTRAST41 SATURATION = cv.CV_CAP_PROP_SATURATION42 HUE = cv.CV_CAP_PROP_HUE43 GAIN = cv.CV_CAP_PROP_GAIN44 EXPOSURE = cv.CV_CAP_PROP_EXPOSURE45 CONVERT_RGB = cv.CV_CAP_PROP_CONVERT_RGB46 RECTIFICATION = cv.CV_CAP_PROP_RECTIFICATION47 elif '3.0+' == OPENCV_VERSION:48 FRAME_WIDTH = cv2.CAP_PROP_FRAME_WIDTH49 FRAME_HEIGHT = cv2.CAP_PROP_FRAME_HEIGHT50 POS_MSEC = cv2.CAP_PROP_POS_MSEC51 POS_FRAMES = cv2.CAP_PROP_POS_FRAMES52 AVI_RATIO = cv2.CAP_PROP_POS_AVI_RATIO53 FPS = cv2.CAP_PROP_FPS54 FOURCC = cv2.CAP_PROP_FOURCC55 FRAME_COUNT = cv2.CAP_PROP_FRAME_COUNT56 FORMAT = cv2.CAP_PROP_FORMAT57 MODE = cv2.CAP_PROP_MODE58 BRIGHTNESS = cv2.CAP_PROP_BRIGHTNESS59 CONTRAST = cv2.CAP_PROP_CONTRAST60 SATURATION = cv2.CAP_PROP_SATURATION61 HUE = cv2.CAP_PROP_HUE62 GAIN = cv2.CAP_PROP_GAIN63 EXPOSURE = cv2.CAP_PROP_EXPOSURE64 CONVERT_RGB = cv2.CAP_PROP_CONVERT_RGB65 RECTIFICATION = cv2.CAP_PROP_RECTIFICATION66 else:67 raise OpencvImportError, 'import cv2.cv error!!!'68 def __init__(self, id):69 """70 camera init71 :param id: camera ID72 :return:73 """74 # assert isinstance(id, int), 'id must be int'75 # assert id>=0, 'id must >= 0'76 object.__init__(self)77 self.__CamId = id78 self.__Ready = False79 self.__Param = {}80 self.__Capture = None81 @property82 def Ready(self):83 return self.__Ready84 def __open(self, resolution, timeout=5):85 self.Logger.debug('opening %r' % self.__CamId)86 Start = time.time()87 self.__Capture = cv2.VideoCapture(self.__CamId)88 if not self.__Capture.isOpened():89 self.Logger.error('can not open [ID]%d camera!' % self.__CamId)90 raise CameraSettingError, 'open camera error!'91 if resolution is not None:92 self.Logger.debug('resolution: %s' % str(resolution))93 while True:94 time.sleep(0.01)95 Width = self.__Capture.get(self.FRAME_WIDTH)96 Height = self.__Capture.get(self.FRAME_HEIGHT)97 if Width == resolution[0] and Height == resolution[1]:98 self.Logger.debug('resolution set ok')99 break100 else:101 time.sleep(0.01)102 self.__Capture.set(self.FRAME_WIDTH, resolution[0])103 self.__Capture.set(self.FRAME_HEIGHT, resolution[1])104 # check timeout105 if time.time() - Start > timeout:106 self.Logger.error('time out')107 raise CameraSettingError, 'camera resolution setting error'108 # self.__Ready = True109 while True:110 time.sleep(0.1)111 Ret, _ = self.__Capture.read()112 if Ret:113 # self.__Ready = True114 break115 # check timeout116 if time.time() - Start > timeout:117 self.Logger.error('time out')118 raise CameraSettingError, 'camera resolution setting error'119 self.__Ready = True120 self.Logger.debug('camera opened')121 def open(self, resolution=None, thread=False):122 if thread:123 MyThread = threading.Thread(target=self.__open, args=(resolution, ))124 MyThread.start()125 else:126 self.__open(resolution=resolution)127 def __config(self, resolution=(1280, 720), hue=0.5, saturation=0.5, brightness=0.5, contrast=0.5):128 self.__Ready = False129 self.__Capture.set(self.FRAME_WIDTH, resolution[0])130 self.__Capture.set(self.FRAME_HEIGHT, resolution[1])131 self.__Capture.set(self.HUE, hue)132 self.__Capture.set(self.SATURATION, saturation)133 self.__Capture.set(self.BRIGHTNESS, brightness)134 self.__Capture.set(self.CONTRAST, contrast)135 self.__Ready = True136 def config(self, resolution=(1280, 720), hue=0.5, saturation=0.5, brightness=0.5, contrast=0.5, thread=False):137 assert self.__Capture is not None, 'self.__Capture can not be none!!!'138 if thread:139 MyThread = threading.Thread(target=self.__config, args=(resolution, hue, saturation, brightness, contrast))140 MyThread.start()141 else:142 self.__config(resolution=resolution, hue=hue, saturation=saturation, brightness=brightness, contrast=contrast)143 def get(self, propId):144 return self.__Capture.get(propId)145 def set(self, propId, value):146 return self.__Capture.set(propId, value)147 def getParams(self):148 assert self.__Capture is not None, 'self.__Capture can not be None!!!'149 if not self.__Capture.isOpened() or not self.__Ready:150 return None151 self.__Param['HEIGHT'] = self.__Capture.get(self.FRAME_HEIGHT)152 self.__Param['WIDTH'] = self.__Capture.get(self.FRAME_WIDTH)153 self.__Param['POS_MSEC'] = self.__Capture.get(self.POS_MSEC)154 self.__Param['POS_FRAMES'] = self.__Capture.get(self.POS_FRAMES)155 self.__Param['POS_AVI_RATIO'] = self.__Capture.get(self.AVI_RATIO)156 self.__Param['FPS'] = self.__Capture.get(self.FPS)157 self.__Param['FOURCC'] = self.__Capture.get(self.FOURCC)158 self.__Param['FRAME_COUNT'] = self.__Capture.get(self.FRAME_COUNT)159 self.__Param['FORMAT'] = self.__Capture.get(self.FORMAT)160 self.__Param['MODE'] = self.__Capture.get(self.MODE)161 self.__Param['BRIGHTNESS'] = self.__Capture.get(self.BRIGHTNESS)162 self.__Param['CONTRAST'] = self.__Capture.get(self.CONTRAST)163 self.__Param['SATURATION'] = self.__Capture.get(self.SATURATION)164 self.__Param['HUE'] = self.__Capture.get(self.HUE)165 self.__Param['GAIN'] = self.__Capture.get(self.GAIN)166 self.__Param['EXPOSURE'] = self.__Capture.get(self.EXPOSURE)167 self.__Param['CONVERT_RGB'] = self.__Capture.get(self.CONVERT_RGB)168 # self.__Param['WHITE_BALANCE'] = self.__Capture.get(self.WHITE_BALANCE)169 self.__Param['RECTIFICATION'] = self.__Capture.get(self.RECTIFICATION)170 return self.__Param171 def isopened(self):172 return self.__Capture.isOpened()173 def takePhoto(self):174 if not self.__Ready:175 return None176 self.isCatch, self.img = self.__Capture.read()177 if self.isCatch:178 return self.img179 return None180 def release(self, thread=False):181 if thread:182 MyThread = threading.Thread(target=self.__release, args=())183 MyThread.start()184 else:185 self.__release()186 def __release(self):187 self.Logger.debug('release.. %d' % self.__CamId)188 self.__Ready = False189 if self.__Capture is not None:190 if self.__Capture.isOpened():191 self.__Capture.release()192 self.Logger.debug('released %d' % self.__CamId)193 def testFrameRate(self):194 if not self.__Ready:195 return None196 else:197 UseTime = []198 Start = time.time()199 while True:200 Now = time.time()201 PassTime = Now - Start202 if PassTime > 3:203 break204 img = self.takePhoto()205 if img is not None:206 UseTime.append(time.time()-Start)207 TimeEsp = np.array(UseTime[1:]) - np.array(UseTime[:-1])208 FrameRate = 1.0 / TimeEsp[1:].mean()209 return FrameRate210 @classmethod211 def __openCams(cls, cameraCaptureList, resolutionList):212 for i in range(len(cameraCaptureList)):213 # cls.Logger.debug('opening %d' % i)214 cameraCaptureList[i].open(resolution=resolutionList[i], thread=False)215 time.sleep(0.1)216 cls.Logger.debug('opened')217 @classmethod218 def openCams(cls, cameraCaptureList, resolutionList, thread=True):219 assert isinstance(cameraCaptureList, list), 'cameraCaptureList must be list'220 assert isinstance(resolutionList, list), 'resolutionList must be list'221 assert len(resolutionList) == len(cameraCaptureList), 'the length of 2 lists must equaled'222 assert cameraCaptureList, 'cameraCaptureList should have at least one element'223 assert isinstance(cameraCaptureList[0], CameraCapture), 'the element os cameraCaptureList must be [class] CameraCapture'224 if thread:225 MyThread = threading.Thread(target=cls.__openCams, args=(cameraCaptureList, resolutionList))226 MyThread.start()227 else:228 cls.__openCams(cameraCaptureList=cameraCaptureList, resolutionList=resolutionList)229 @classmethod230 def __releaseCams(cls, cameraCaptureList, NOP):231 for i in range(len(cameraCaptureList)):232 # cls.Logger.debug('opening %d' % i)233 cameraCaptureList[i].release(thread=False)234 time.sleep(0.1)235 # cls.Logger.debug('released')236 @classmethod237 def releaseCams(cls, cameraCaptureList, NOP=None, thread=True):238 assert isinstance(cameraCaptureList, list), 'cameraCaptureList must be list'239 assert cameraCaptureList, 'cameraCaptureList should have at least one element'240 assert isinstance(cameraCaptureList[0], CameraCapture), 'the element os cameraCaptureList must be [class] CameraCapture'241 if thread:242 MyThread = threading.Thread(target=cls.__releaseCams, args=(cameraCaptureList, NOP))243 MyThread.start()244 else:245 cls.__releaseCams(cameraCaptureList=cameraCaptureList, NOP=NOP)246# if __name__ == '__main__':247# Cam = CameraCapture(4)248# # Cam.open(thread=False, resolution=(640, 480))249# Cam.open(thread=False, resolution=(1600, 1200))250# # CameraCapture.openCams([Cam], [None], True)251# # Cam.open(thread=False, resolution=(1600, 1200))252# num = 0253# T0 = time.time()254# count = 0255# while True:256# # print 'num: ', num257# # num += 1258# time.sleep(0.1)259# Img = Cam.takePhoto()260# if Img is None:261# PassTime = time.time() - T0262# if PassTime > count:263# print 'Passed ', PassTime, 'second'264# count += 1265# if count > 10:266# break267# continue268#269# T0 = time.time()270# cv2.imshow('img', Img)271# Key = chr(cv2.waitKey(10) & 255)272# if 'q' == Key:273# break274#275# print Cam.set(propId=CameraCapture.BRIGHTNESS, value=0)276# print Cam.set(propId=CameraCapture.BRIGHTNESS, value=0)277# print 'frame_height', Cam.get(propId=CameraCapture.FRAME_HEIGHT)278# print 'FrameRate: ', Cam.testFrameRate()279# print 'Param:\n', Cam.getParams()280# Cam.release()281# # print 'aaaaaa'282 283# # # ---------------------------------- Stereo Cam ---------------------------------- #284# if __name__ == '__main__':285# Cam5 = CameraCapture(2)286# Cam7 = CameraCapture(4)287# Wait5FrameFlag = 5288# CameraCapture.openCams(cameraCaptureList=[Cam5, Cam7],289# resolutionList=[(1600, 1200), (1600, 1200)], thread=False)290#291# while True:292# SrcImg0 = Cam5.takePhoto()293# SrcImg1 = Cam7.takePhoto()294#295# if None in (SrcImg0, SrcImg1):296# NowTime = time.time()297# if PreTime is None:298# PreTime = NowTime - 0.51299# if NowTime - PreTime >= 0.5:300# PreTime = NowTime301# continue302#303# if Wait5FrameFlag > 0:304# if Wait5FrameFlag == 5:305# print 'start: ', time.time()306# startWait = time.time()307# SaveStart = time.time()308# cv2.imwrite('../../Datas/Img/CatchTail/waitFrameImgTest_Cam0_'+str(Wait5FrameFlag)+'.png', SrcImg0)309# cv2.imwrite('../../Datas/Img/CatchTail/waitFrameImgTest_Cam1_'+str(Wait5FrameFlag)+'.png', SrcImg1)310# print 'Save time: ', time.time() - SaveStart311# Wait5FrameFlag -= 1312# if Wait5FrameFlag == 0:313# print 'end: ', time.time()314# print '5 Frame: ', time.time() - startWait315# continue316#317#318# cv2.imshow('img0', SrcImg0)319# cv2.imshow('img1', SrcImg1)320# Key = chr(cv2.waitKey(5) & 0xff)321# if 'q' == Key:322# break323# print 'cam 5 FrameRate: ', Cam5.testFrameRate()324# print 'cam 7 FrameRate: ', Cam7.testFrameRate()325# # ---------------------------------- 2 Pair of Stereo Cam ---------------------------------- #326# if __name__ == '__main__':327# Cam5 = CameraCapture(2)328# Cam7 = CameraCapture(4)329# Cam3 = CameraCapture(0)330# Cam4 = CameraCapture(1)331# CamPairList = [[Cam3, Cam4], [Cam5, Cam7]]332#333# PairNum = 0334# TimeNum = 0335# while True:336# start = time.time()337# print 'the ', TimeNum, ' time'338# TimeNum += 1339# if PairNum > 1:340# PairNum = 0341# CamPair = CamPairList[PairNum]342# print 'now open...'343# print 'camera pair: ', PairNum344# # use new way345# CameraCapture.setCamsResolution(cameraCaptureList=CamPair, resolutionList=[(1600, 1200), (1600, 1200)], thread=True)346# # old method347# # for Cam in CamPair:348# # # Cam.open(resolution=(1600, 1200), thread=False)349# # Cam.open(resolution=(1600, 1200), thread=True)350# # end351# while True:352# # PassTime = time.time() - start353# # print 'PassTime: ', PassTime354# if time.time() - start > 10:355# for Cam in CamPair:356# Cam.release()357# time.sleep(1)358# break359# Img0 = CamPair[0].takePhoto()360# Img1 = CamPair[1].takePhoto()361# if None in (Img0, Img1):362# continue363# cv2.imshow('Img0_'+str(PairNum), cv2.resize(Img0, (Img0.shape[1]/4, Img0.shape[0]/4)))364# cv2.imshow('Img1_'+str(PairNum), cv2.resize(Img1, (Img1.shape[1]/4, Img1.shape[0]/4)))365# Key = chr(cv2.waitKey(5) & 0xff)366# if 'q' == Key:367# raise KeyBoardQuitSignal, 'pressed [q] in program'368# PairNum += 1369if __name__ == '__main__':370 Cam = CameraCapture(2)371 # Cam2 = CameraCapture(1)372 Cam.open(resolution=[1600, 1200])373 # Cam.open(resolution=(1280, 720))374 # CameraCapture.openCams([Cam], [[1280, 720]])375 while True:376 Img = Cam.takePhoto()377 if Img is not None:378 cv2.imshow('Img', Img)379 Key = chr(cv2.waitKey(0) & 255)380 if Key == 'q':381 break...

Full Screen

Full Screen

stable.py

Source:stable.py Github

copy

Full Screen

1import cv22import numpy as np3from tqdm import tqdm4import argparse5import os6from PIL import Image7import PIL8import sys9#os.environ["CUDA_VISIBLE_DEVICES"]="0"10# get param11name='brisk'12parser = argparse.ArgumentParser(description='')13parser.add_argument('-v', type=str, default=r'C:\\Users\\Eddy\\Desktop\\test.mp4') # 指定输入视频路径位置(参数必选)14parser.add_argument('-o', type=str, default=r'C:\\Users\\Eddy\\Desktop\\output\\'+name+'_out.mp4') # 指定输出视频路径位置(参数必选)15parser.add_argument('-n', type=int, default=-1) # 指定处理的帧数(参数可选), 不设置使用视频实际帧16parser.add_argument('-model', type=str, default=name) # 指定处理的帧数(参数可选), 不设置使用视频实际帧17# eg: python3 stable.py -v=video/01.mp4 -o=video/01_stable.mp4 -n=100 -p=618args = parser.parse_args()19#args = parser.parse_known_args()[0]20input_path = args.v21output_path = args.o22number = args.n23model = args.model24if model not in ['sift','surf','brisk','freak','orb','akaze']:25 print('Wrong model')26 sys.exit()27#default28#index_params = dict(algorithm=6, table_number=6, key_size=12)29if model=='sift' or model=='surf':30 index_params = dict(algorithm=0, trees=5)31elif model=='orb':32 index_params = dict(algorithm=6, table_number=6, key_size=12)33else:34 index_params = dict(algorithm=6, table_number=6, key_size=12)35def keypointToPoint(keypoint):36 point = np.zeros(len(keypoint) * 2, np.float32)37 for i in range(len(keypoint)):38 point[i * 2] = keypoint[i].pt[0]39 point[i * 2 + 1] = keypoint[i].pt[1]40 point = point.reshape(-1, 2)41 return point42def drawMatchesKnn_cv2(img1_gray,kp1,img2_gray,kp2,goodMatch):43 h1, w1 = img1_gray.shape[:2]44 h2, w2 = img2_gray.shape[:2]45 vis = np.zeros((max(h1, h2), w1 + w2, 3), np.uint8)46 vis[:h1, :w1] = img1_gray47 vis[:h2, w1:w1 + w2] = img2_gray48 p1 = [kpp.queryIdx for kpp in goodMatch]49 p2 = [kpp.trainIdx for kpp in goodMatch]50 post1 = np.int32([kp1[pp].pt for pp in p1])51 post2 = np.int32([kp2[pp].pt for pp in p2]) + (w1, 0)52 for (x1, y1), (x2, y2) in zip(post1, post2):53 cv2.line(vis, (x1, y1), (x2, y2), (0,0,255))54 img11=Image.fromarray(vis)55 img11.save(r'C:\\Users\\Eddy\\Desktop\\match.png')56 #cv2.namedWindow("match",cv2.WINDOW_NORMAL)57 #cv2.imshow("match", vis)58class Stable:59 # 处理视频文件路径60 __input_path = None61 __output_path = None62 __number = number63 # surf 特征提取64 __surf = {65 # surf算法66 'surf': None,67 # 提取的特征点68 'kp': None,69 # 描述符70 'des': None,71 # 过滤后的特征模板72 'template_kp': None73 }74 # capture75 __capture = {76 # 捕捉器77 'cap': None,78 # 视频大小79 'size': None,80 # 视频总帧81 'frame_count': None,82 # 视频帧率83 'fps': None,84 # 视频85 'video': None,86 }87 # 配置88 __config = {89 # 要保留的最佳特征的数量90 'key_point_count': 5000,91 # Flann特征匹配92 #SIFT and SURF93 #'index_params': dict(algorithm=0, trees=5),94 #ORB95 #FLANN_INDEX_LSH=696 #'index_params': dict(algorithm=6, table_number=6, key_size=12),97 'index_params': index_params,98 'search_params': dict(checks=50),99 'ratio': 0.5,100 }101 # 特征提取列表102 __surf_list = []103 def __init__(self):104 pass105 # 初始化capture106 def __init_capture(self):107 self.__capture['cap'] = cv2.VideoCapture(self.__video_path)108 self.__capture['size'] = (int(self.__capture['cap'].get(cv2.CAP_PROP_FRAME_WIDTH)),109 int(self.__capture['cap'].get(cv2.CAP_PROP_FRAME_HEIGHT)))110 self.__capture['fps'] = self.__capture['cap'].get(cv2.CAP_PROP_FPS)111 self.__capture['video'] = cv2.VideoWriter(self.__output_path, cv2.VideoWriter_fourcc(*"mp4v"),112 self.__capture['fps'], self.__capture['size'])113 self.__capture['frame_count'] = int(self.__capture['cap'].get(cv2.CAP_PROP_FRAME_COUNT))114 if number == -1:115 self.__number = self.__capture['frame_count']116 else:117 self.__number = min(self.__number, self.__capture['frame_count'])118 # 初始化surf119 def __init_surf(self):120 self.__capture['cap'].set(cv2.CAP_PROP_POS_FRAMES, 0)121 state, first_frame = self.__capture['cap'].read()122 self.__capture['cap'].set(cv2.CAP_PROP_POS_FRAMES, self.__capture['frame_count'] - 1)123 state, last_frame = self.__capture['cap'].read()124 # mask125 mask=np.zeros([first_frame.shape[0],first_frame.shape[1]],dtype=np.uint8)126 mask[143:1500,508:1700]=255127 first_frame=cv2.add(first_frame,np.zeros(np.shape(first_frame),dtype=np.uint8),mask=mask)128 last_frame=cv2.add(last_frame,np.zeros(np.shape(last_frame),dtype=np.uint8),mask=mask)129 # default model ORB130 if model=='sift':131 self.__surf['surf'] = cv2.xfeatures2d.SIFT_create(self.__config['key_point_count'])132 elif model=='surf':133 self.__surf['surf'] = cv2.xfeatures2d.SURF_create(self.__config['key_point_count'])134 elif model=='orb':135 self.__surf['surf'] = cv2.ORB_create(self.__config['key_point_count'])136 elif model=='brisk':137 self.__surf['surf'] = cv2.BRISK_create()138 elif model=='freak':139 self.__surf['surf'] = cv2.Freak_create()140 elif model=='akaze':141 self.__surf['surf'] = cv2.AKAZE_create()142 self.__surf['kp'], self.__surf['des'] = self.__surf['surf'].detectAndCompute(first_frame, None)143 kp, des = self.__surf['surf'].detectAndCompute(last_frame, None)144 # for p in keypointToPoint(self.__surf['kp']):145 # cv2.circle(first_frame, (p[0],p[1]), 3, (0, 0, 255), -1)146 #147 # im_f=Image.fromarray(first_frame)148 # im_f.save('C:\\Users\\Eddy\\Desktop\\first5.png')149 #150 # for p in keypointToPoint(kp):151 # cv2.circle(last_frame, (p[0],p[1]), 3, (0, 0, 255), -1)152 #153 # im_f=Image.fromarray(last_frame)154 # im_f.save('C:\\Users\\Eddy\\Desktop\\last5.png')155 #img1=cv2.drawKeypoints(first_frame,self.__surf['kp'],None,(255,0,0),cv2.DRAW_MATCHES_FLAGS_DEFAULT)156 img1=cv2.drawKeypoints(first_frame,self.__surf['kp'],None,(255,0,0),cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)157 #img1=cv2.drawKeypoints(first_frame,self.__surf['kp'],None,(255,0,0),cv2.DRAW_MATCHES_FLAGS_DRAW_OVER_OUTIMG)158 #img1=cv2.drawKeypoints(first_frame,self.__surf['kp'],None,(255,0,0),cv2.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINT)159 img1=Image.fromarray(img1)160 img1.save(r'C:\\Users\\Eddy\\Desktop\\output\\'+model+'_first_frame.png')161 #img2=cv2.drawKeypoints(last_frame,kp,None,(255,0,0),cv2.DRAW_MATCHES_FLAGS_DEFAULT)162 img2=cv2.drawKeypoints(last_frame,kp,None,(255,0,0),cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)163 #img2=cv2.drawKeypoints(last_frame,kp,None,(255,0,0),cv2.DRAW_MATCHES_FLAGS_DRAW_OVER_OUTIMG)164 #img2=cv2.drawKeypoints(last_frame,kp,None,(255,0,0),cv2.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINT)165 img2=Image.fromarray(img2)166 img2.save(r'C:\\Users\\Eddy\\Desktop\\output\\'+model+'_last_frame.png')167 # 快速临近匹配168 flann = cv2.FlannBasedMatcher(self.__config['index_params'], self.__config['search_params'])169 matches = flann.knnMatch(self.__surf['des'], des, k=2)170 good_match = []171 for m, n in matches:172 if m.distance < self.__config['ratio'] * n.distance:173 good_match.append(m)174 #drawMatchesKnn_cv2(first_frame,self.__surf['kp'],last_frame,kp,good_match)175 img_out=cv2.drawMatches(first_frame,self.__surf['kp'],last_frame,kp,good_match[:50],last_frame,flags=2)176 img_out=Image.fromarray(img_out)177 img_out.save(r'C:\\Users\\Eddy\\Desktop\\output\\'+model+'_match.png')178 self.__surf['template_kp'] = []179 for f in good_match:180 self.__surf['template_kp'].append(self.__surf['kp'][f.queryIdx])181 # 释放182 def __release(self):183 self.__capture['video'].release()184 self.__capture['cap'].release()185 # 处理186 def __process(self):187 current_frame = 1188 self.__capture['cap'].set(cv2.CAP_PROP_POS_FRAMES, 0)189 process_bar = tqdm(self.__number, position=current_frame)190 while current_frame <= self.__number:191 # 抽帧192 success, frame = self.__capture['cap'].read()193 if not success: return194 # 计算195 frame = self.detect_compute(frame)196 # 写帧197 self.__capture['video'].write(frame)198 current_frame += 1199 process_bar.update(1)200 # 视频稳像201 def stable(self, input_path, output_path, number):202 self.__video_path = input_path203 self.__output_path = output_path204 self.__number = number205 self.__init_capture()206 self.__init_surf()207 self.__process()208 self.__release()209 # 特征点提取210 def detect_compute(self, frame):211 frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)212 # 计算特征点213 kp, des = self.__surf['surf'].detectAndCompute(frame_gray, None)214 # 快速临近匹配215 flann = cv2.FlannBasedMatcher(self.__config['index_params'], self.__config['search_params'])216 matches = flann.knnMatch(self.__surf['des'], des, k=2)217 # 计算单应性矩阵218 good_match = []219 for m, n in matches:220 if m.distance < self.__config['ratio'] * n.distance:221 good_match.append(m)222 # 特征模版过滤223 p1, p2 = [], []224 for f in good_match:225 if self.__surf['kp'][f.queryIdx] in self.__surf['template_kp']:226 p1.append(self.__surf['kp'][f.queryIdx].pt)227 p2.append(kp[f.trainIdx].pt)228 # 单应性矩阵229 H, _ = cv2.findHomography(np.float32(p2), np.float32(p1), cv2.RHO)230 # 透视变换231 output_frame = cv2.warpPerspective(frame, H, self.__capture['size'], borderMode=cv2.BORDER_REPLICATE)232 return output_frame233if __name__ == '__main__':234 if not os.path.exists(input_path):235 print(f'[ERROR] File "{input_path}" not found')236 exit(0)237 else:238 print(f'[INFO] Video "{input_path}" stable begin')239 s = Stable()240 s.stable(input_path, output_path, number)241 print('[INFO] Done.')...

Full Screen

Full Screen

webcam.py

Source:webcam.py Github

copy

Full Screen

1import collections2import time3import cv24import numpy as np5class WebcamSource:6 """7 Helper class for OpenCV VideoCapture. Can be used as an iterator.8 """9 def __init__(self, camera_id=0, width=1280, height=720, fps=30, buffer_size=1):10 self.__name = "WebcamSource"11 self.__capture = cv2.VideoCapture(camera_id)12 self.__capture.set(cv2.CAP_PROP_FRAME_WIDTH, width)13 self.__capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height)14 self.__capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))15 self.__capture.set(cv2.CAP_PROP_FPS, fps)16 self.__capture.set(cv2.CAP_PROP_BUFFERSIZE, buffer_size)17 self.buffer_size = buffer_size18 self.prev_frame_time = 019 self.new_frame_time = 020 self.fps_deque = collections.deque(maxlen=fps)21 def __iter__(self):22 if not self.__capture.isOpened():23 raise StopIteration24 return self25 def __next__(self):26 """27 Get next frame from webcam or stop iteration when no frame can be grabbed from webcam28 :return: None29 """30 ret, frame = self.__capture.read()31 if not ret:32 raise StopIteration33 if cv2.waitKey(1) & 0xFF == ord('q'):34 raise StopIteration35 return frame36 def clear_frame_buffer(self):37 for _ in range(self.buffer_size):38 self.__capture.read()39 def __del__(self):40 self.__capture.release()41 cv2.destroyAllWindows()42 def show(self, frame, only_print=False):43 self.new_frame_time = time.time()44 self.fps_deque.append(1 / (self.new_frame_time - self.prev_frame_time))45 self.prev_frame_time = self.new_frame_time46 if only_print:47 print(f'{self.__name} - FPS: {np.mean(self.fps_deque):5.2f}')48 else:49 cv2.imshow('show_frame', frame)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ATX automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful