# import roslibimportroslibroslib.load_manifest("my_package")# import other required librariesimportsysimportrospyimportcv2fromstd_msgs.msgimportStringfromsensor_msgs.msgimportImagefromcv_bridgeimportCvBridge,CvBridgeErrorfromvidgear.gearsimportVideoGear# custom publisher classclassimage_publisher:def__init__(self,source=0,logging=False):# create CV bridgeself.bridge=CvBridge()# define publisher topicself.image_pub=rospy.Publisher("image_topic_pub",Image)# open stream with given parametersself.stream=VideoGear(source=source,logging=logging).start()# define publisher topicrospy.Subscriber("image_topic_sub",Image,self.callback)defcallback(self,data):# {do something with received ROS node data here}# read framesframe=self.stream.read()# check for frame if None-typeifnot(frameisNone):# {do something with the frame here}# publish our frametry:self.image_pub.publish(self.bridge.cv2_to_imgmsg(frame,"bgr8"))exceptCvBridgeErrorase:# catch any errorsprint(e)defclose(self):# stop streamself.stream.stop()defmain(args):# !!! define your own video source here !!!# Open any video stream such as live webcam# video stream on first index(i.e. 0) device# define publisheric=image_publisher(source=0,logging=True)# initiate ROS node on publisherrospy.init_node("image_publisher",anonymous=True)try:# run noderospy.spin()exceptKeyboardInterrupt:print("Shutting down")finally:# close publisheric.close()if__name__=="__main__":main(sys.argv)
Here's a high-level wrapper code around VideoGear API to enable auto-reconnection during capturing, plus stabilization is enabled (stabilize=True) in order to stabilize captured frames on-the-go:
New in v0.2.2
This example was added in v0.2.2.
Enforcing UDP stream
You can easily enforce UDP for RTSP streams inplace of default TCP, by putting following lines of code on the top of your existing code:
fromvidgear.gearsimportVideoGearimportcv2importdatetimeimporttimeclassReconnecting_VideoGear:def__init__(self,cam_address,stabilize=False,reset_attempts=50,reset_delay=5):self.cam_address=cam_addressself.stabilize=stabilizeself.reset_attempts=reset_attemptsself.reset_delay=reset_delayself.source=VideoGear(source=self.cam_address,stabilize=self.stabilize).start()self.running=Truedefread(self):ifself.sourceisNone:returnNoneifself.runningandself.reset_attempts>0:frame=self.source.read()ifframeisNone:self.source.stop()self.reset_attempts-=1print("Re-connection Attempt-{} occured at time:{}".format(str(self.reset_attempts),datetime.datetime.now().strftime("%m-%d-%Y %I:%M:%S%p"),))time.sleep(self.reset_delay)self.source=VideoGear(source=self.cam_address,stabilize=self.stabilize).start()# return previous framereturnself.frameelse:self.frame=framereturnframeelse:returnNonedefstop(self):self.running=Falseself.reset_attempts=0self.frame=Noneifnotself.sourceisNone:self.source.stop()if__name__=="__main__":# open any valid video streamstream=Reconnecting_VideoGear(cam_address="rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov",reset_attempts=20,reset_delay=5,)# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if None-typeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
Using VideoGear for Real-time Stabilization with Audio Encoding¶
In this example code, we will be directly merging the audio from a Video-File (to be stabilized) with its processed stabilized frames into a compressed video output in real time:
New in v0.2.4
This example was added in v0.2.4.
Make sure this input video-file (to be stabilized) contains valid audio source, otherwise you could encounter multiple errors or no output at all.
You MUST use -input_framerate attribute to set exact value of input framerate when using external audio in Real-time Frames mode, otherwise audio delay will occur in output streams.
Use -disable_force_termination flag when video duration is too short(<60sec), otherwise WriteGear will not produce any valid output.
# import required librariesfromvidgear.gearsimportWriteGearfromvidgear.gearsimportVideoGearimportcv2# Give suitable video file path to be stabilizedunstabilized_videofile="test.mp4"# open any valid video path with stabilization enabled(`stabilize = True`)stream_stab=VideoGear(source=unstabilized_videofile,stabilize=True,logging=True).start()# define required FFmpeg optimizing parameters for your writeroutput_params={"-i":unstabilized_videofile,"-c:a":"aac","-input_framerate":stream_stab.framerate,"-clones":["-shortest"],# !!! Uncomment following line if video duration is too short(<60sec). !!!#"-disable_force_termination": True,}# Define writer with defined parameters and suitable output filename for e.g. `Output.mp4writer=WriteGear(output="Output.mp4",logging=True,**output_params)# loop overwhileTrue:# read frames from streamframe_stab=stream_stab.read()# check for frame if not grabbedifframe_stabisNone:break# {do something with the stabilized frame here}# write stabilized frame to writerwriter.write(frame_stab)# safely close streamsstream_stab.stop()# safely close writerwriter.close()