在 Mac OSX 中测试 Ros OpenCV3 摄像头

在 Mac OSX 中测试 Ros OpenCV3 摄像头

#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <sstream>
using namespace cv;

int main(int argc, char** argv)
{
    ros::init(argc, argv, "image_publisher");
    ros::NodeHandle nh;
    image_transport::ImageTransport it(nh);
    image_transport::Publisher img_pub = it.advertise("camera/camera_image", 1);
    image_transport::Publisher cap_pub = it.advertise("camera/video_image", 1);

    Mat image = imread("/Users/fitsir/Pictures/superman.jpg", CV_LOAD_IMAGE_COLOR);
    sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", image).toImageMsg();    

    VideoCapture cap(0);   //打开摄像头
    if (!cap.isOpened())   // isOpened函数用来检测VideoCapture类是否打开成功
    {
        return -1;
    }
    Mat frame;
    sensor_msgs::ImagePtr cap_msg;


    ros::Rate loop_rate(5);
    while (nh.ok()) {
        cap >> frame;
        if (!frame.empty()) {
            cap_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", frame).toImageMsg();
            cap_pub.publish(cap_msg);
        }
        img_pub.publish(msg);

        ros::spinOnce();
        loop_rate.sleep();
    }

}
#!/usr/bin/env python
from __future__ import print_function
import cv2
import rospy
from std_msgs.msg import String
import cv_bridge



def main():
    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10)

    cap = cv2.VideoCapture(0)
    test = cap.get(cv2.CAP_PROP_POS_MSEC)
    ratio = cap.get(cv2.CAP_PROP_POS_AVI_RATIO)
    frame_rate = cap.get(cv2.CAP_PROP_FPS)
    width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
    brightness = cap.get(cv2.CAP_PROP_BRIGHTNESS)
    contrast = cap.get(cv2.CAP_PROP_CONTRAST)
    saturation = cap.get(cv2.CAP_PROP_SATURATION)
    hue = cap.get(cv2.CAP_PROP_HUE)
    gain = cap.get(cv2.CAP_PROP_GAIN)
    exposure = cap.get(cv2.CAP_PROP_EXPOSURE)
    print("Test: ", test)
    print("Ratio: ", ratio)
    print("Frame Rate: ", frame_rate)
    print("Height: ", height)
    print("Width: ", width)
    print("Brightness: ", brightness)
    print("Contrast: ", contrast)
    print("Saturation: ", saturation)
    print("Hue: ", hue)
    print("Gain: ", gain)
    print("Exposure: ", exposure)
    while not rospy.is_shutdown():
        hello_str = "hello world %s" % rospy.get_time()
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
        rate.sleep()

        ret, img = cap.read()
        cv2.imshow("input", img)

        key = cv2.waitKey(10)
        if key == 27:
            break

    cv2.destroyAllWindows()
    cv2.VideoCapture(0).release()



if __name__ == '__main__':
    main()