Skip to content

Commit

Permalink
Add opencv video publisher (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
pockerman committed Dec 24, 2023
1 parent 4172c14 commit 93acdc8
Show file tree
Hide file tree
Showing 9 changed files with 222 additions and 0 deletions.
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
"""
ROS2 program to publish real-time streaming video from your built-in webcam
"""
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import cv2

NODE_NAME: str = "opencv_video_publisher"
TOPIC_NAME: str ="opencv_video_frames"
IMAGES_QUEUE_SIZE = 10
PUBLISH_MESSAGE_RATE: float = 5.0


class OpenCVVideoPublisher(Node):
"""
Create an ImagePublisher class, which is a subclass of the Node class.
"""

def __init__(self, topic_name: str=TOPIC_NAME,
images_queue_size: int = IMAGES_QUEUE_SIZE,
publish_message_rate: float=PUBLISH_MESSAGE_RATE):
"""
Class constructor to set up the node
"""
# Initiate the Node class's constructor and give it a name
super().__init__(NODE_NAME)

# Create the publisher. This publisher will publish an Image
# to the video_frames topic. The queue size is 10 messages.
self.publisher_ = self.create_publisher(Image, topic_name, images_queue_size)

# We will publish a message every 0.1 seconds
timer_period = 0.1 # seconds

# Create the timer
self.timer = self.create_timer(publish_message_rate, self.timer_callback)

# Create a VideoCapture object
# The argument '0' gets the default webcam.
self.cap = cv2.VideoCapture(0)

# Used to convert between ROS and OpenCV images
self.br = CvBridge()

self.get_logger().info(f'Finished {NODE_NAME} initialization')
self.get_logger().info(f'{NODE_NAME} publishes on topic {topic_name}')
self.get_logger().info(f'{NODE_NAME} images_queue_size {images_queue_size}')
self.get_logger().info(f'{NODE_NAME} publish message rate {publish_message_rate}')

def timer_callback(self):
"""
Callback function.
This function gets called every 0.1 seconds.
"""

# Capture frame-by-frame
# This method returns True/False as well
# as the video frame.
ret, frame = self.cap.read()

if ret == True:
# Publish the image.
# The 'cv2_to_imgmsg' method converts an OpenCV
# image to a ROS 2 image message
self.publisher_.publish(self.br.cv2_to_imgmsg(frame))

# Display the message on the console
self.get_logger().info('Publishing video frame')

def main(args=None):

# Initialize the rclpy library
rclpy.init(args=args)

# Create the node
image_publisher = OpenCVVideoPublisher(topic_name=TOPIC_NAME,
images_queue_size=IMAGES_QUEUE_SIZE,
publish_message_rate=PUBLISH_MESSAGE_RATE)

# Spin the node so the callback function is called.
rclpy.spin(image_publisher)

# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
image_publisher.destroy_node()

# Shutdown the ROS client library for Python
rclpy.shutdown()

if __name__ == '__main__':
main()
25 changes: 25 additions & 0 deletions ros_packages/learn_ros/src/opencv_video_publisher/package.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>opencv_video_publisher</name>
<version>0.0.0</version>
<description>TODO: Package description</description>
<maintainer email="a.giavaras@gmail.com">alex</maintainer>
<license>TODO: License declaration</license>

<depend>rclpy</depend>
<depend>image_transport</depend>
<depend>cv_bridge</depend>
<depend>sensor_msgs</depend>
<depend>std_msgs</depend>
<depend>opencv2</depend>

<test_depend>ament_copyright</test_depend>
<test_depend>ament_flake8</test_depend>
<test_depend>ament_pep257</test_depend>
<test_depend>python3-pytest</test_depend>

<export>
<build_type>ament_python</build_type>
</export>
</package>
Empty file.
4 changes: 4 additions & 0 deletions ros_packages/learn_ros/src/opencv_video_publisher/setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[develop]
script_dir=$base/lib/opencv_video_publisher
[install]
install_scripts=$base/lib/opencv_video_publisher
26 changes: 26 additions & 0 deletions ros_packages/learn_ros/src/opencv_video_publisher/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from setuptools import find_packages, setup

package_name = 'opencv_video_publisher'

setup(
name=package_name,
version='0.0.0',
packages=find_packages(exclude=['test']),
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='alex',
maintainer_email='a.giavaras@gmail.com',
description='TODO: Package description',
license='TODO: License declaration',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'opencv_video_publisher = opencv_video_publisher.opencv_video_publisher:main',
],
},
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Copyright 2015 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from ament_copyright.main import main
import pytest


# Remove the `skip` decorator once the source file(s) have a copyright header
@pytest.mark.skip(reason='No copyright header has been placed in the generated source file.')
@pytest.mark.copyright
@pytest.mark.linter
def test_copyright():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found errors'
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Copyright 2017 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from ament_flake8.main import main_with_errors
import pytest


@pytest.mark.flake8
@pytest.mark.linter
def test_flake8():
rc, errors = main_with_errors(argv=[])
assert rc == 0, \
'Found %d code style errors / warnings:\n' % len(errors) + \
'\n'.join(errors)
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Copyright 2015 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from ament_pep257.main import main
import pytest


@pytest.mark.linter
@pytest.mark.pep257
def test_pep257():
rc = main(argv=['.', 'test'])
assert rc == 0, 'Found code style errors / warnings'

0 comments on commit 93acdc8

Please sign in to comment.