diff --git a/src/Perspective.cpp b/src/Perspective.cpp index 1172393..de2a354 100644 --- a/src/Perspective.cpp +++ b/src/Perspective.cpp @@ -17,6 +17,7 @@ #include "pattern.h" #include "proto/vision/ssl_vision_wrapper.pb.h" #include "log.h" +#include "config.h" #include @@ -39,16 +40,16 @@ void Perspective::geometryCheck(const int width, const int height, const double bool calibFound = false; for(const SSL_GeometryCameraCalibration& calib : socket->getGeometry().calib()) { - if(calib.camera_id() == camId) { + if(calib.camera_id() == config.camera_id()) { calibFound = true; model = CameraModel(calib); if(!calib.has_derived_camera_world_tx() || !calib.has_derived_camera_world_ty() || !calib.has_derived_camera_world_tz()) { - socket->send(model.getProto(camId)); + socket->send(model.getProto(config.camera_id())); SSL_WrapperPacket wrapper; wrapper.set_source(SSL_SOURCE_VISION_PROCESSOR); wrapper.mutable_geometry()->CopyFrom(socket->getGeometry()); wrapper.mutable_geometry()->clear_calib(); - wrapper.mutable_geometry()->add_calib()->CopyFrom(model.getProto(camId)); + wrapper.mutable_geometry()->add_calib()->CopyFrom(model.getProto(config.camera_id())); socket->send(wrapper); } break; @@ -105,8 +106,8 @@ void Perspective::geometryCheck(const int width, const int height, const double } // clamp to field boundaries - const float halfLength = (float)field.field_length()/2.0f + goalBoundaryWidth(field) + geometryTolerance; - const float halfWidth = (float)field.field_width()/2.0f + (float)field.boundary_width() + geometryTolerance; + const float halfLength = (float)field.field_length()/2.0f + goalBoundaryWidth(field) + config.thresholds().geometry_tolerance(); + const float halfWidth = (float)field.field_width()/2.0f + (float)field.boundary_width() + config.thresholds().geometry_tolerance(); visibleFieldExtent[0] = std::max(visibleFieldExtent[0], -halfLength); visibleFieldExtent[1] = std::min(visibleFieldExtent[1], halfLength); visibleFieldExtent[2] = std::max(visibleFieldExtent[2], -halfWidth); diff --git a/src/Perspective.h b/src/Perspective.h index 5cab4a3..aa7a3de 100644 --- a/src/Perspective.h +++ b/src/Perspective.h @@ -31,7 +31,7 @@ typedef struct __attribute__ ((packed)) { class Perspective { public: - Perspective(std::shared_ptr socket, int camId, float geometryTolerance): socket(std::move(socket)), camId(camId), geometryTolerance(geometryTolerance) {} + Perspective(std::shared_ptr socket): socket(std::move(socket)) {} void geometryCheck(int width, int height, double maxBotHeight, float resamplingFactor); Eigen::Vector2f flat2field(const Eigen::Vector2f& pos) const; @@ -53,6 +53,4 @@ class Perspective { private: const std::shared_ptr socket; - const unsigned int camId; - const float geometryTolerance; }; diff --git a/src/Resources.cpp b/src/Resources.cpp index 0bd01d6..cd486ad 100644 --- a/src/Resources.cpp +++ b/src/Resources.cpp @@ -67,7 +67,7 @@ static YAML::Node getOptional(const YAML::Node& node) { return node.IsDefined() ? node : YAML::Node(); } -Resources::Resources(const std::string& configPath) : fieldReference(), configPath(configPath) { +Resources::Resources(const std::string& configPath) : configPath(configPath) { YAML::Node config = YAML::LoadFile(configPath); struct stat st{}; if(stat(configPath.c_str(), &st) == 0) @@ -75,32 +75,8 @@ Resources::Resources(const std::string& configPath) : fieldReference(), configPa openCl = std::make_shared(); - CameraConfig camConfig(getOptional(config["camera"])); - camera = openCamera(camConfig); - camera->setResolution(camConfig.width, camConfig.height); - camera->setExposure(camConfig.exposure); - camera->setGain(camConfig.gain); - camera->setGamma(camConfig.gamma); - camera->setWhiteBalance(camConfig.whiteBalanceType, camConfig.whiteBalanceBlue, camConfig.whiteBalanceRed); - - camId = config["cam_id"].as(0); - if (camId < 0 || camId > 7) { - FATAL("Invalid camera ID, must be >= 0 and <= 7: " << camId); - } - - maxBlobs = getOptional(config["thresholds"])["blobs"].as(2000); - geometryTolerance = getOptional(config["thresholds"])["geometry_tolerance"].as(10.0f); - applyTunables(config); - orange = orangeReference; - field = fieldReference; - yellow = yellowReference; - blue = blueReference; - green = greenReference; - pink = pinkReference; - fieldLineColor = fieldReference; - YAML::Node geometry = getOptional(config["geometry"]); cameraAmount = geometry["camera_amount"].as(1); cameraHeight = geometry["camera_height"].as(0.0); @@ -117,12 +93,10 @@ Resources::Resources(const std::string& configPath) : fieldReference(), configPa YAML::Node network = getOptional(config["network"]); gcSocket = std::make_shared(network["gc_ip"].as("224.5.23.1"), network["gc_port"].as(10003), YAML::LoadFile(config["bot_heights_file"].as("robot-heights.yml")).as>()); - socket = std::make_shared(network["vision_ip"].as("224.5.23.2"), network["vision_port"].as(10006), camId, gcSocket->defaultBotHeight); - perspective = std::make_shared(socket, camId, geometryTolerance); + socket = std::make_shared(network["vision_ip"].as("224.5.23.2"), network["vision_port"].as(10006), gcSocket->defaultBotHeight); + perspective = std::make_shared(socket); YAML::Node stream = getOptional(config["stream"]); - rtpStreamer = std::make_shared(stream["active"].as(true), "rtp://" + stream["ip_base_prefix"].as("224.5.23.") + std::to_string(stream["ip_base_end"].as(100) + camId) + ":" + std::to_string(stream["port"].as(10100))); - rawFeed = stream["raw_feed"].as(false); snapshotWriter = std::make_shared(); raw2quadKernel = openCl->compile(kernel_raw2quad_cl, camera->format().kernelOptions); @@ -173,7 +147,7 @@ void Resources::rgba2blobCenter(const std::shared_ptr* channels, std::s void Resources::streamQuad(std::shared_ptr* channels) { std::shared_ptr nv12 = openCl->acquireNV12(channels[0]->width, channels[0]->height); openCl->await(quad2nv12, cl::EnqueueArgs(cl::NDRange(channels[0]->width, channels[0]->height)), channels[0]->image, channels[1]->image, channels[2]->image, channels[3]->image, nv12->buffer); - rtpStreamer->sendFrame(nv12); + rtpStreamer.sendFrame(nv12); } void Resources::streamImage(CLImage &img) { @@ -189,31 +163,12 @@ void Resources::streamImage(CLImage &img) { std::shared_ptr nv12 = openCl->acquireNV12(img.width, img.height); openCl->await(kernel, cl::EnqueueArgs(cl::NDRange(img.width, img.height)), img.image, nv12->buffer); - rtpStreamer->sendFrame(nv12); + rtpStreamer.sendFrame(nv12); } void Resources::applyTunables(const YAML::Node& config) { YAML::Node thresholds = getOptional(config["thresholds"]); - minCircularity = thresholds["circularity"].as(15.0); - minScore = thresholds["score"].as(5.0); - minConfidence = thresholds["min_confidence"].as(0.2f); - minCamEdgeDistance = thresholds["min_cam_edge_distance"].as(170.0); resamplingFactor = thresholds["resampling_factor"].as(1.0f); - clippingTolerance = thresholds["clipping_tolerance"].as(10.0f); - - YAML::Node tracking = getOptional(config["tracking"]); - minTrackingRadius = tracking["min_tracking_radius"].as(20.0); - maxBotAcceleration = 1000 * tracking["max_bot_acceleration"].as(6.5); - - YAML::Node color = getOptional(config["color"]); - referenceForce = color["reference_force"].as(0.1f); - historyForce = color["history_force"].as(0.7f); - orangeReference = color["orange"].as(Eigen::Vector3i{192, 128, 64}); - fieldReference = color["field"].as(Eigen::Vector3i{128, 128, 128}); - yellowReference = color["yellow"].as(Eigen::Vector3i{255, 128, 0}); - blueReference = color["blue"].as(Eigen::Vector3i{0, 128, 255}); - greenReference = color["green"].as(Eigen::Vector3i{0, 255, 128}); - pinkReference = color["pink"].as(Eigen::Vector3i{255, 0, 128}); YAML::Node debug = getOptional(config["debug"]); debugImages = debug["debug_images"].as(false); diff --git a/src/Resources.h b/src/Resources.h index 76be6f9..ed24d35 100644 --- a/src/Resources.h +++ b/src/Resources.h @@ -19,7 +19,6 @@ #include #include #include -#include "driver/cameradriver.h" #include "rtpstreamer.h" #include "snapshotwriter.h" #include "udpsocket.h" @@ -42,37 +41,7 @@ class Resources { void reloadConfigIfChanged(); - std::unique_ptr camera = nullptr; - - int camId; - - double minTrackingRadius; - double maxBotAcceleration; // mm/s² - - double minCircularity; - double minScore; - double minCamEdgeDistance; - int maxBlobs; - float minConfidence; float resamplingFactor; - float clippingTolerance; - float geometryTolerance; - - float referenceForce; - float historyForce; - Eigen::Vector3i orangeReference; - Eigen::Vector3i fieldReference; - Eigen::Vector3i yellowReference; - Eigen::Vector3i blueReference; - Eigen::Vector3i greenReference; - Eigen::Vector3i pinkReference; - Eigen::Vector3i orange; - Eigen::Vector3i field; - Eigen::Vector3i yellow; - Eigen::Vector3i blue; - Eigen::Vector3i green; - Eigen::Vector3i pink; - Eigen::Vector3i fieldLineColor = fieldReference; int cameraAmount; double cameraHeight; // Just for calibration, do not use elsewhere (0.0 as special value for automatic calibration) @@ -86,13 +55,11 @@ class Resources { std::string groundTruth; bool debugImages; int debugStreamIntervalMs; - bool rawFeed; std::shared_ptr gcSocket; std::shared_ptr socket; std::shared_ptr perspective; std::shared_ptr openCl; - std::shared_ptr rtpStreamer; std::shared_ptr snapshotWriter; cl::Kernel raw2quadKernel; diff --git a/src/blob_benchmark.cpp b/src/blob_benchmark.cpp index 9ce93ff..67c83fa 100644 --- a/src/blob_benchmark.cpp +++ b/src/blob_benchmark.cpp @@ -16,6 +16,8 @@ #include #include #include "Resources.h" +#include "driver/cameradriver.h" +#include "config.h" #include "GroundTruth.h" #include "pattern.h" #include "cl_kernels.h" @@ -134,7 +136,7 @@ int main(int argc, char* argv[]) { while(true) { double startTime = getRealTime(); - std::shared_ptr img = r.camera->readImage(); + std::shared_ptr img = camera->readImage(); if(img == nullptr) break; @@ -151,7 +153,7 @@ int main(int argc, char* argv[]) { r.rgba2blobCenter(channels, flat, gradDot, blobCenter); //std::shared_ptr score = r.openCl->acquire(&PixelFormat::F32, r.perspective->reprojectedFieldSize[0], r.perspective->reprojectedFieldSize[1], img->name); - //OpenCL::await(scoreKernel, cl::EnqueueArgs(cl::NDRange(r.perspective->reprojectedFieldSize[0], r.perspective->reprojectedFieldSize[1])), flat->image, blobCenter->image, score->image, (float)r.minCircularity, (int)floor(r.minBlobRadius/r.perspective->fieldScale)); + //OpenCL::await(scoreKernel, cl::EnqueueArgs(cl::NDRange(r.perspective->reprojectedFieldSize[0], r.perspective->reprojectedFieldSize[1])), flat->image, blobCenter->image, score->image, config.thresholds().circularity(), (int)floor(r.minBlobRadius/r.perspective->fieldScale)); processingTime += getRealTime() - startTime; startTime = getRealTime(); diff --git a/src/blobs/colorupdate.cpp b/src/blobs/colorupdate.cpp index a3c2a29..d16ea23 100644 --- a/src/blobs/colorupdate.cpp +++ b/src/blobs/colorupdate.cpp @@ -1,6 +1,9 @@ #include "colorupdate.h" #include "kmeans.h" #include "pattern.h" +#include "config.h" +#include "proto/vision/ssl_vp_config.pb.h" +#include static float sqPointLineSegmentDistance(const SSL_FieldLineSegment& line, const Eigen::Vector2f& point) { @@ -18,7 +21,7 @@ static bool ballAtLine(const Resources& r, const BallHypothesis& ball) { const Eigen::Vector2f imgPos = r.perspective->model.field2image({ball.pos.x(), ball.pos.y(), (float)r.gcSocket->maxBotHeight}); const Eigen::Vector2f ballPos = r.perspective->model.image2field(imgPos, r.perspective->field.ball_radius()).head<2>(); - const float maxLineDistance = (float)r.perspective->field.line_thickness()/2 + r.geometryTolerance; + const float maxLineDistance = (float)r.perspective->field.line_thickness()/2 + config.thresholds().geometry_tolerance(); const float sqMaxLineDistance = maxLineDistance*maxLineDistance; for(const auto& line : r.perspective->field.field_lines()) { @@ -52,22 +55,19 @@ static void determineFieldLineBlobColor(Resources& r, const std::list 2) - r.fieldLineColor = colorSum /= amount; + liveFieldLineColor = colorSum /= amount; } -static inline void updateColor(const Resources& r, const Eigen::Vector3i& reference, const Eigen::Vector3i& oldColor, Eigen::Vector3i& color) { - const float updateForce = 1.0f - r.referenceForce - r.historyForce; - color = (r.referenceForce*reference.cast() + r.historyForce*oldColor.cast() + updateForce*color.cast()).cast(); +static inline void updateColor(VPColor* field, const Eigen::Vector3i& color) { + const float updateForce = 1.0f - config.color().reference_force() - config.color().history_force(); + Eigen::Vector3f newColor = config.color().reference_force()*eigen_from_color(field->reference()).cast() + + config.color().history_force()*eigen_from_color(field->live()).cast() + + updateForce*color.cast(); + + field->mutable_live()->CopyFrom(color_from_eigen(newColor.cast())); } void updateColors(Resources& r, const std::list>& bestBotModels, const std::list>& ballCandidates) { - Eigen::Vector3i oldField = r.field; - Eigen::Vector3i oldOrange = r.orange; - Eigen::Vector3i oldYellow = r.yellow; - Eigen::Vector3i oldBlue = r.blue; - Eigen::Vector3i oldGreen = r.green; - Eigen::Vector3i oldPink = r.pink; - std::vector centerBlobs; Eigen::Vector3i pink(0, 0, 0); int pinkN = 0; @@ -94,27 +94,30 @@ void updateColors(Resources& r, const std::list>& } if(pinkN > 0) { - r.pink = pink / pinkN; - updateColor(r, r.pinkReference, oldPink, r.pink); + updateColor(config.mutable_color()->mutable_pink(), pink / pinkN); } if(greenN > 0) { - r.green = green / greenN; - updateColor(r, r.greenReference, oldGreen, r.green); + updateColor(config.mutable_color()->mutable_green(), green / greenN); } - if(kMeans(r.pink, centerBlobs, r.yellow, r.blue)) { - updateColor(r, r.yellowReference, oldYellow, r.yellow); - updateColor(r, r.blueReference, oldBlue, r.blue); + Eigen::Vector3i yellow = liveYellow; + Eigen::Vector3i blue = liveBlue; + if(kMeans(livePink, centerBlobs, yellow, blue)) { + updateColor(config.mutable_color()->mutable_yellow(), yellow); + updateColor(config.mutable_color()->mutable_blue(), blue); } std::vector ballBlobs; for (const auto& ball : ballCandidates) ballBlobs.push_back(ball->blob->center); - if(kMeans(r.blue, ballBlobs, r.orange, r.field)) { - updateColor(r, r.orangeReference, oldOrange, r.orange); - updateColor(r, r.fieldReference, oldField, r.field); + Eigen::Vector3i orange = liveOrange; + Eigen::Vector3i field = liveField; + if(kMeans(liveBlue, ballBlobs, orange, field)) { + updateColor(config.mutable_color()->mutable_orange(), orange); + updateColor(config.mutable_color()->mutable_field(), field); } determineFieldLineBlobColor(r, ballCandidates); + apply_color_update(); } diff --git a/src/blobs/hypothesis.cpp b/src/blobs/hypothesis.cpp index 7e6d919..7a8ca39 100644 --- a/src/blobs/hypothesis.cpp +++ b/src/blobs/hypothesis.cpp @@ -14,6 +14,7 @@ limitations under the License. */ #include "hypothesis.h" +#include "config.h" #include "kmeans.h" #include "pattern.h" @@ -81,9 +82,9 @@ void BallHypothesis::addToDetectionFrame(const Resources& r, SSL_DetectionFrame* } void BallHypothesis::calcColorScore(const Resources& r) { - int falseOrange = (blob->color - r.field).squaredNorm(); - int orange = (blob->color - r.orange).squaredNorm(); - int fieldLine = (blob->color - r.fieldLineColor).squaredNorm(); + int falseOrange = (blob->color - liveField).squaredNorm(); + int orange = (blob->color - liveOrange).squaredNorm(); + int fieldLine = (blob->color - liveFieldLineColor).squaredNorm(); if (falseOrange <= orange || fieldLine <= orange) { score = 0; @@ -116,7 +117,7 @@ bool BotHypothesis::isClipping(const Resources& r, const BotHypothesis& other) c float minDistance = (abs(selfAngle) < MIN_ROBOT_OPENING_ANGLE ? MIN_ROBOT_FRONT_DISTANCE/cosf(selfAngle) : MIN_ROBOT_RADIUS) + (abs(otherAngle) < MIN_ROBOT_OPENING_ANGLE ? MIN_ROBOT_FRONT_DISTANCE/cosf(otherAngle) : MIN_ROBOT_RADIUS) - - r.clippingTolerance; + - config.thresholds().clipping_tolerance(); return sqDistance < minDistance*minDistance; } @@ -133,7 +134,7 @@ bool BotHypothesis::isClipping(const Resources& r, const BallHypothesis& ball) c if(abs(angle) >= MIN_ROBOT_OPENING_ANGLE) return true; - minDistance = (MIN_ROBOT_FRONT_DISTANCE + clippedBallRadius) / cosf(angle) - r.clippingTolerance; + minDistance = (MIN_ROBOT_FRONT_DISTANCE + clippedBallRadius) / cosf(angle) - config.thresholds().clipping_tolerance(); return sqDistance < minDistance*minDistance; } @@ -214,11 +215,11 @@ void DetectionBotHypothesis::recalcPostColorCalib(const Resources& r) { } void DetectionBotHypothesis::calcBotId(const Resources& r) { - Eigen::Vector3i green = r.green; - Eigen::Vector3i pink = r.pink; + Eigen::Vector3i green = liveGreen; + Eigen::Vector3i pink = livePink; kMeans(blobs[0]->color, {blobs[1]->color, blobs[2]->color, blobs[3]->color, blobs[4]->color}, green, pink); - botId = ((blobs[0]->color - r.blue).squaredNorm() < (blobs[0]->color - r.yellow).squaredNorm() ? 16 : 0) + patternLUT[ + botId = ((blobs[0]->color - liveBlue).squaredNorm() < (blobs[0]->color - liveYellow).squaredNorm() ? 16 : 0) + patternLUT[ (((blobs[1]->color - green).squaredNorm() < (blobs[1]->color - pink).squaredNorm() ? 1 : 0) << 3) + (((blobs[2]->color - green).squaredNorm() < (blobs[2]->color - pink).squaredNorm()? 1 : 0) << 2) + (((blobs[3]->color - green).squaredNorm() < (blobs[3]->color - pink).squaredNorm() ? 1 : 0) << 1) + @@ -256,11 +257,11 @@ void TrackedBotHypothesis::calcTrackingScore(const Resources& r) { Eigen::Vector3i blobColor; Eigen::Vector3i oppositeColor; if(i == 0) { - blobColor = botId >= 16 ? r.blue : r.yellow; - oppositeColor = botId >= 16 ? r.yellow : r.blue; + blobColor = botId >= 16 ? liveBlue : liveYellow; + oppositeColor = botId >= 16 ? liveYellow : liveBlue; } else { - blobColor = ((patterns[botId % 16] >> (4-i)) & 1) ? r.green : r.pink; - oppositeColor = ((patterns[botId % 16] >> (4-i)) & 1) ? r.pink : r.green; + blobColor = ((patterns[botId % 16] >> (4-i)) & 1) ? liveGreen : livePink; + oppositeColor = ((patterns[botId % 16] >> (4-i)) & 1) ? livePink : liveGreen; } if((blob->color - oppositeColor).squaredNorm() - (blob->color - blobColor).squaredNorm() <= 0) { diff --git a/src/calib/GeomModel.cpp b/src/calib/GeomModel.cpp index aa40e4c..e7ab44f 100644 --- a/src/calib/GeomModel.cpp +++ b/src/calib/GeomModel.cpp @@ -20,6 +20,7 @@ #include "LineDetection.h" #include "proto/vision/ssl_vision_wrapper.pb.h" #include "log.h" +#include "config.h" #include @@ -30,7 +31,7 @@ float dist(const cv::Vec2f& v1, const cv::Vec2f& v2) { } void visibleFieldExtent(const Resources &r, const bool withBoundary, Eigen::Vector2f &min, Eigen::Vector2f &max) { - return visibleFieldExtentEstimation(r.camId, r.cameraAmount, r.socket->getGeometry().field(), withBoundary, min, max); + return visibleFieldExtentEstimation(config.camera_id(), r.cameraAmount, r.socket->getGeometry().field(), withBoundary, min, max); } Eigen::Vector2f cv2eigen(const cv::Vec2f& v) { @@ -475,10 +476,10 @@ static bool cornerCalibration(const Resources& r, const std::vectorgetGeometry().field()); + CameraModel model({thresholded.cols, thresholded.rows}, config.camera_id(), r.cameraAmount, (float)r.cameraHeight, r.socket->getGeometry().field()); //drawModel(r, thresholded, linePixels, model); //thresholded.save(".initial.png"); @@ -582,7 +583,7 @@ void geometryCalibration(const Resources& r, const CLImage& rgba) { wrapper.set_source(SSL_SOURCE_VISION_PROCESSOR); wrapper.mutable_geometry()->CopyFrom(r.socket->getGeometry()); wrapper.mutable_geometry()->clear_calib(); - wrapper.mutable_geometry()->add_calib()->CopyFrom(model.getProto(r.camId)); + wrapper.mutable_geometry()->add_calib()->CopyFrom(model.getProto(config.camera_id())); r.socket->send(wrapper); drawModel(r, thresholded, linePixels, model); diff --git a/src/config.cpp b/src/config.cpp index 6415f72..0cc0992 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -1,4 +1,5 @@ #include "config.h" +#include "driver/cameradriver.h" #include @@ -9,18 +10,29 @@ static YAML::Node getOptional(const YAML::Node& node) { return node.IsDefined() ? node : YAML::Node(); } -static void set_color(VPColor* color, const YAML::Node& node, int r, int g, int b) { - color->mutable_reference()->set_red(node[0].as(r)); - color->mutable_reference()->set_green(node[1].as(g)); - color->mutable_reference()->set_blue(node[2].as(b)); +static void set_color(VPColor* color, int r, int g, int b) { + color->mutable_reference()->set_red(r); + color->mutable_reference()->set_green(g); + color->mutable_reference()->set_blue(b); color->mutable_live()->CopyFrom(color->reference()); } +static void set_color(VPColor* color, const YAML::Node& node, int r, int g, int b) { + set_color(color, node[0].as(r), node[1].as(g), node[2].as(b)); +} + void init_config(const std::string& configPath) { char host[256]; gethostname(host, 256); config.set_instance(host); + set_color(config.mutable_color()->mutable_orange(), 192, 128, 64); + set_color(config.mutable_color()->mutable_field(), 128, 128, 128); + set_color(config.mutable_color()->mutable_yellow(), 255, 128, 0); + set_color(config.mutable_color()->mutable_blue(), 0, 128, 255); + set_color(config.mutable_color()->mutable_green(), 0, 255, 128); + set_color(config.mutable_color()->mutable_pink(), 255, 0, 128); + // Interim copy from config file until network config is fully operational YAML::Node yaml = YAML::LoadFile(configPath); config.set_camera_id(yaml["cam_id"].as(0)); @@ -41,7 +53,7 @@ void init_config(const std::string& configPath) { config.mutable_camera()->set_driver(DUMMY); } config.mutable_camera()->set_id(getOptional(yaml["camera"])["id"].as(0)); - config.mutable_camera()->set_path(getOptional(yaml["camera"])["path"].as("/dev/video" + std::to_string(config.camera().id()))); + config.mutable_camera()->set_path(getOptional(yaml["camera"])["device"].as("/dev/video" + std::to_string(config.camera().id()))); config.mutable_camera()->set_width(getOptional(yaml["camera"])["width"].as(0)); config.mutable_camera()->set_height(getOptional(yaml["camera"])["height"].as(0)); config.mutable_camera()->set_exposure(getOptional(yaml["camera"])["exposure"].as(0.0)); @@ -89,4 +101,53 @@ void init_config(const std::string& configPath) { config.mutable_stream()->set_active(getOptional(yaml["stream"])["active"].as(true)); config.mutable_stream()->set_stream_ip(getOptional(yaml["stream"])["ip_base_prefix"].as("224.5.23.") + std::to_string(getOptional(yaml["stream"])["ip_base_end"].as(100) + config.camera_id())); config.mutable_stream()->set_stream_port(getOptional(yaml["stream"])["port"].as(10100)); + + liveFieldLineColor = eigen_from_color(config.color().field().live()); + apply_color_update(); +} + +void apply_received_config(Resources& r) { + SSL_VPConfig received = r.socket->getReceivedConfig(); + + if(received.has_camera_id()) + config.set_camera_id(received.camera_id()); + + //TODO robot heights + update_camera_config(&received.camera()); + //TODO geometry + config.mutable_thresholds()->MergeFrom(received.thresholds()); + config.mutable_color()->MergeFrom(received.color()); + apply_color_update(); + //TODO network + rtpStreamer.updateConfig(received.stream()); + //TODO wait for geometry +} + +Eigen::Vector3i liveOrange; +Eigen::Vector3i liveField; +Eigen::Vector3i liveYellow; +Eigen::Vector3i liveBlue; +Eigen::Vector3i liveGreen; +Eigen::Vector3i livePink; +Eigen::Vector3i liveFieldLineColor; + +Color color_from_eigen(const Eigen::Vector3i& eigen) { + Color color; + color.set_red(eigen[0]); + color.set_green(eigen[1]); + color.set_blue(eigen[2]); + return color; +} + +Eigen::Vector3i eigen_from_color(const Color& color) { + return Eigen::Vector3i(color.red(), color.green(), color.blue()); +} + +void apply_color_update() { + liveOrange = eigen_from_color(config.color().orange().live()); + liveField = eigen_from_color(config.color().orange().live()); + liveYellow = eigen_from_color(config.color().orange().live()); + liveBlue = eigen_from_color(config.color().orange().live()); + liveGreen = eigen_from_color(config.color().orange().live()); + livePink = eigen_from_color(config.color().orange().live()); } diff --git a/src/config.h b/src/config.h index 108d8d3..96f955d 100644 --- a/src/config.h +++ b/src/config.h @@ -1,6 +1,21 @@ #pragma once #include "vision/ssl_vp_config.pb.h" +#include "Resources.h" extern SSL_VPConfig config; +// Live used colors duplicated as Eigen vectors for performance reasons, shall be modified through apply_color_update() only. +extern Eigen::Vector3i liveOrange; +extern Eigen::Vector3i liveField; +extern Eigen::Vector3i liveYellow; +extern Eigen::Vector3i liveBlue; +extern Eigen::Vector3i liveGreen; +extern Eigen::Vector3i livePink; +extern Eigen::Vector3i liveFieldLineColor; + void init_config(const std::string& configPath); +void apply_received_config(Resources& r); + +Color color_from_eigen(const Eigen::Vector3i& eigen); +Eigen::Vector3i eigen_from_color(const Color& color); +void apply_color_update(); diff --git a/src/driver/cameradriver.cpp b/src/driver/cameradriver.cpp index db2577a..7f45f57 100644 --- a/src/driver/cameradriver.cpp +++ b/src/driver/cameradriver.cpp @@ -14,8 +14,11 @@ limitations under the License. */ #include "cameradriver.h" +#include "config.h" +#include "driver/dummydriver.h" #include "driver/opencvdriver.h" +#include #ifdef SPINNAKER_AVAILABLE #include "driver/spinnakerdriver.h" #endif @@ -26,9 +29,9 @@ #include "driver/dc1394driver.h" #endif -#include double realTimeOffset = 0.0; + double getRealTime() { return (double)std::chrono::duration_cast(std::chrono::high_resolution_clock::now().time_since_epoch()).count() / 1e6 + realTimeOffset; } @@ -37,66 +40,78 @@ double CameraDriver::getTime() { return getRealTime(); } +std::unique_ptr camera; -CameraConfig::CameraConfig(const YAML::Node &cam) { - driverType = cam["driver"].as("SPINNAKER"); - - hardwareId = cam["id"].as(0); - // "path" is the former name of "device" - device = cam["device"].as(cam["path"].as(driverType == "OPENCV" ? "/dev/video" + std::to_string(this->hardwareId) : "")); - - width = cam["width"].as(0); - height = cam["height"].as(0); - exposure = cam["exposure"].as(0.0); - gain = cam["gain"].as(0.0); - gamma = cam["gamma"].as(1.0); - - const YAML::Node wb = cam["white_balance"].IsDefined() ? cam["white_balance"] : YAML::Node(); - if(wb.IsMap()) { - whiteBalanceBlue = wb["blue"].as(1.0); - whiteBalanceRed = wb["red"].as(1.0); - } else { - whiteBalanceType = (wb.as("OUTDOOR") == "OUTDOOR") - ? WhiteBalanceType_AutoOutdoor - : WhiteBalanceType_AutoIndoor; - } -} - -bool CameraConfig::autoResolution() const { - return width == 0 || height == 0; -} - -bool CameraConfig::autoExposure() const { - return exposure == 0.0; -} - -bool CameraConfig::autoGain() const { - return gain == 0.0; -} - -bool CameraConfig::autoGamma() const { - return gamma == 1.0; +void init_camera() { + camera = std::make_unique(); } - -std::unique_ptr openCamera(const CameraConfig& config) { +void update_camera_config(const SSL_VPConfigCamera* camera_config) { + bool newInstance = false; + + SSL_VPConfigCameraDriver driver = (camera_config->has_driver() ? *camera_config : config.camera()).driver(); + uint32_t id = (camera_config->has_id() ? *camera_config : config.camera()).id(); + std::string device = (camera_config->has_path() ? *camera_config : config.camera()).path(); + if(driver != config.camera().driver() || id != config.camera().id() || device != config.camera().path()) { + newInstance = true; + + switch(camera_config->driver()) { + case DUMMY: + camera = std::make_unique(); + break; + case OPENCV: + if(device.empty()) + device = "/dev/video" + std::to_string(id); + + camera = std::make_unique(device); + break; #ifdef SPINNAKER_AVAILABLE - if(config.driverType == "SPINNAKER") - return std::make_unique(config); + case SPINNAKER: + camera = std::make_unique(device, id); + break; #endif - #ifdef MVIMPACT_AVAILABLE - if(config.driverType == "MVIMPACT") - return std::make_unique(config); + case MVIMPACT: + camera = std::make_unique(id); + break; #endif - #ifdef DC1394_AVAILABLE - if(config.driverType == "DC1394") - return std::make_unique(config); + case DC1394: + camera = std::make_unique(id); + break; #endif + default: + WARN("Attempted to configure invalid/unavailable camera driver: " << camera_config->driver()); + } + } + + uint32_t width = (camera_config->has_width() ? *camera_config : config.camera()).width(); + uint32_t height = (camera_config->has_height() ? *camera_config : config.camera()).height(); + if(newInstance || width != config.camera().width() || height != config.camera().height()) { + camera->setResolution(width, height); + } + + float exposure = (camera_config->has_exposure() ? *camera_config : config.camera()).exposure(); + if(newInstance || exposure != config.camera().exposure()) { + camera->setExposure(exposure); + } + + float gain = (camera_config->has_gain() ? *camera_config : config.camera()).gain(); + if(newInstance || gain != config.camera().gain()) { + camera->setGain(gain); + } - if(config.driverType == "OPENCV") - return std::make_unique(config); + float gamma = (camera_config->has_gamma() ? *camera_config : config.camera()).gamma(); + if(newInstance || gamma != config.camera().gamma()) { + camera->setGamma(gamma); + } + + SSL_VPConfigCameraWBType wbType = (camera_config->has_wb_type() ? *camera_config : config.camera()).wb_type(); + float wbRed = (camera_config->has_wb_red() ? *camera_config : config.camera()).wb_red(); + float wbBlue = (camera_config->has_wb_blue() ? *camera_config : config.camera()).wb_blue(); + if(newInstance || wbType != config.camera().wb_type() || wbRed != config.camera().wb_red() || wbBlue != config.camera().wb_blue()) { + camera->setWhiteBalance(wbType, wbBlue, wbRed); + } - FATAL("Unknown camera/image driver defined: " << config.driverType); + config.mutable_camera()->MergeFrom(*camera_config); } diff --git a/src/driver/cameradriver.h b/src/driver/cameradriver.h index 1a8c74e..1d97f86 100644 --- a/src/driver/cameradriver.h +++ b/src/driver/cameradriver.h @@ -16,21 +16,13 @@ #pragma once #include -#include #include "opencl.h" +#include "vision/ssl_vp_config.pb.h" extern double realTimeOffset; double getRealTime(); -enum WhiteBalanceType { - WhiteBalanceType_Manual, - // Separate outdoor and indoor auto profiles for cameras with different auto algorithms (e.g. Spinnaker) - WhiteBalanceType_AutoOutdoor, - WhiteBalanceType_AutoIndoor -}; - - /** Abstract camera interface for the implementation of arbitrary camera interfaces. */ class CameraDriver { public: @@ -58,39 +50,14 @@ class CameraDriver { virtual float getGamma() = 0; virtual void setGamma(float gamma) = 0; - virtual WhiteBalanceType getWhiteBalanceType() = 0; + virtual SSL_VPConfigCameraWBType getWhiteBalanceType() = 0; virtual float getWhiteBalanceBlue() = 0; virtual float getWhiteBalanceRed() = 0; - virtual void setWhiteBalance(WhiteBalanceType type, float blue, float red) = 0; + virtual void setWhiteBalance(SSL_VPConfigCameraWBType type, float blue, float red) = 0; }; -/** Wrapper for camera options contained in the cam section of config.yml. */ -class CameraConfig { -public: - CameraConfig(const YAML::Node& cam); - - bool autoResolution() const; - bool autoExposure() const; - bool autoGain() const; - bool autoGamma() const; - - std::string driverType; - - int hardwareId; - std::string device; // Takes precedence over hardwareId. OpenCV: device or file path, with fallback to /dev/video{hardwareId}. Spinnaker: serial number - - int width; - int height; - double exposure; - double gain; - double gamma; - - WhiteBalanceType whiteBalanceType = WhiteBalanceType_Manual; - double whiteBalanceBlue; - double whiteBalanceRed; - double whiteBalance[2]; -}; - +extern std::unique_ptr camera; -std::unique_ptr openCamera(const CameraConfig& config); +void init_camera(); +void update_camera_config(const SSL_VPConfigCamera* camera_config); diff --git a/src/driver/dc1394driver.cpp b/src/driver/dc1394driver.cpp index 8a1107b..f8c2fa5 100644 --- a/src/driver/dc1394driver.cpp +++ b/src/driver/dc1394driver.cpp @@ -37,11 +37,11 @@ static dc1394camera_t* getCamera(dc1394_t* dc1394, int hardwareId) { return camera; } -DC1394Driver::DC1394Driver(const CameraConfig& config): dc1394(dc1394_new()) { +DC1394Driver::DC1394Driver(uint32_t hardwareId): dc1394(dc1394_new()) { if(dc1394 == nullptr) FATAL("[DC1394] Could not initialize libdc1394"); - camera = getCamera(dc1394, config.hardwareId); + camera = getCamera(dc1394, hardwareId); name = std::string(camera->vendor) + "_" + camera->model; std::replace(name.begin(), name.end(), ' ', '_'); @@ -271,10 +271,10 @@ void DC1394Driver::setGamma(float gamma) { dc1394_feature_set_value(camera, DC1394_FEATURE_GAMMA, gamma < 1.0f ? max : min); } -WhiteBalanceType DC1394Driver::getWhiteBalanceType() { +SSL_VPConfigCameraWBType DC1394Driver::getWhiteBalanceType() { dc1394feature_mode_t featureMode = DC1394_FEATURE_MODE_MANUAL; dc1394_feature_get_mode(camera, DC1394_FEATURE_WHITE_BALANCE, &featureMode); - return featureMode == DC1394_FEATURE_MODE_MANUAL ? WhiteBalanceType_Manual : WhiteBalanceType_AutoOutdoor; + return featureMode == DC1394_FEATURE_MODE_MANUAL ? MANUAL : OUTDOOR; } float DC1394Driver::getWhiteBalanceBlue() { @@ -289,8 +289,8 @@ float DC1394Driver::getWhiteBalanceRed() { return (float)red; } -void DC1394Driver::setWhiteBalance(WhiteBalanceType type, float blue, float red) { - if(!setAuto(DC1394_FEATURE_WHITE_BALANCE, type != WhiteBalanceType_Manual)) +void DC1394Driver::setWhiteBalance(SSL_VPConfigCameraWBType type, float blue, float red) { + if(!setAuto(DC1394_FEATURE_WHITE_BALANCE, type != MANUAL)) return; // IIDC white balance has no standardized unit, the values are the raw U/B and V/R camera registers diff --git a/src/driver/dc1394driver.h b/src/driver/dc1394driver.h index b2990c6..d78ac86 100644 --- a/src/driver/dc1394driver.h +++ b/src/driver/dc1394driver.h @@ -7,7 +7,7 @@ /** IIDC (FireWire) cameras via libdc1394, e.g. AVT Stingray. Captures Format7 mode 0 in YUV422 and converts to BGR8. */ class DC1394Driver : public CameraDriver { public: - explicit DC1394Driver(const CameraConfig& config); + explicit DC1394Driver(uint32_t hardwareId); ~DC1394Driver() override; std::shared_ptr readImage() override; @@ -29,10 +29,10 @@ class DC1394Driver : public CameraDriver { float getGamma() override; void setGamma(float gamma) override; - WhiteBalanceType getWhiteBalanceType() override; + SSL_VPConfigCameraWBType getWhiteBalanceType() override; float getWhiteBalanceBlue() override; float getWhiteBalanceRed() override; - void setWhiteBalance(WhiteBalanceType type, float blue, float red) override; + void setWhiteBalance(SSL_VPConfigCameraWBType type, float blue, float red) override; private: void startCapture(); diff --git a/src/driver/dummydriver.cpp b/src/driver/dummydriver.cpp index c19bff5..c5d100f 100644 --- a/src/driver/dummydriver.cpp +++ b/src/driver/dummydriver.cpp @@ -1,8 +1,7 @@ #include "dummydriver.h" -#include "driver/cameradriver.h" #include "opencl.h" -DummyDriver::DummyDriver(const CameraConfig& config): image(std::make_shared(&PixelFormat::BGR8, 640, 480, "dummy")) {} +DummyDriver::DummyDriver(): image(std::make_shared(&PixelFormat::BGR8, 640, 480, "dummy")) {} std::shared_ptr DummyDriver::readImage() { return image; @@ -44,8 +43,8 @@ float DummyDriver::getGamma() { void DummyDriver::setGamma(float gamma) {} -WhiteBalanceType DummyDriver::getWhiteBalanceType() { - return WhiteBalanceType::WhiteBalanceType_AutoOutdoor; +SSL_VPConfigCameraWBType DummyDriver::getWhiteBalanceType() { + return OUTDOOR; } float DummyDriver::getWhiteBalanceBlue() { @@ -56,4 +55,4 @@ float DummyDriver::getWhiteBalanceRed() { return 1.0f; } -void DummyDriver::setWhiteBalance(WhiteBalanceType type, float blue, float red) {} +void DummyDriver::setWhiteBalance(SSL_VPConfigCameraWBType type, float blue, float red) {} diff --git a/src/driver/dummydriver.h b/src/driver/dummydriver.h index c46d07d..48d5fdc 100644 --- a/src/driver/dummydriver.h +++ b/src/driver/dummydriver.h @@ -3,7 +3,7 @@ class DummyDriver : public CameraDriver { public: - explicit DummyDriver(const CameraConfig& config); + explicit DummyDriver(); ~DummyDriver() override = default; std::shared_ptr readImage() override; @@ -25,10 +25,10 @@ class DummyDriver : public CameraDriver { float getGamma() override; void setGamma(float gamma) override; - WhiteBalanceType getWhiteBalanceType() override; + SSL_VPConfigCameraWBType getWhiteBalanceType() override; float getWhiteBalanceBlue() override; float getWhiteBalanceRed() override; - void setWhiteBalance(WhiteBalanceType type, float blue, float red) override; + void setWhiteBalance(SSL_VPConfigCameraWBType type, float blue, float red) override; private: std::shared_ptr image; diff --git a/src/driver/mvimpactdriver.cpp b/src/driver/mvimpactdriver.cpp index 110cd39..badb099 100644 --- a/src/driver/mvimpactdriver.cpp +++ b/src/driver/mvimpactdriver.cpp @@ -47,7 +47,7 @@ static mvIMPACT::acquire::Device* getDevice(int hardwareId) { return device; } -MVImpactDriver::MVImpactDriver(const CameraConfig& config): device(getDevice(config.hardwareId)), settings(device) { +MVImpactDriver::MVImpactDriver(uint32_t hardwareId): device(getDevice(hardwareId)), settings(device) { settings.cameraSetting.restoreDefault(); settings.imageProcessing.restoreDefault(); settings.imageDestination.restoreDefault(); @@ -143,11 +143,11 @@ void MVImpactDriver::setGamma(float gamma) { // Unsupported? TODO } -WhiteBalanceType MVImpactDriver::getWhiteBalanceType() { +SSL_VPConfigCameraWBType MVImpactDriver::getWhiteBalanceType() { if(settings.imageProcessing.whiteBalanceCalibration.read() != TWhiteBalanceCalibrationMode::wbcmOff) { - return WhiteBalanceType::WhiteBalanceType_AutoOutdoor; + return OUTDOOR; } else { - return WhiteBalanceType::WhiteBalanceType_Manual; + return MANUAL; } } @@ -159,8 +159,8 @@ float MVImpactDriver::getWhiteBalanceRed() { return settings.imageProcessing.getWBUserSetting(0).redGain.read(); } -void MVImpactDriver::setWhiteBalance(WhiteBalanceType type, float blue, float red) { - if(type != WhiteBalanceType_Manual) { +void MVImpactDriver::setWhiteBalance(SSL_VPConfigCameraWBType type, float blue, float red) { + if(type != MANUAL) { settings.imageProcessing.whiteBalanceCalibration.write(TWhiteBalanceCalibrationMode::wbcmContinuous); } else { settings.imageProcessing.whiteBalanceCalibration.write(TWhiteBalanceCalibrationMode::wbcmOff); diff --git a/src/driver/mvimpactdriver.h b/src/driver/mvimpactdriver.h index db0124f..7c9aa63 100644 --- a/src/driver/mvimpactdriver.h +++ b/src/driver/mvimpactdriver.h @@ -23,7 +23,7 @@ class MVImpactDriver : public CameraDriver { public: - explicit MVImpactDriver(const CameraConfig& config); + explicit MVImpactDriver(uint32_t hardwareId); ~MVImpactDriver() override; std::shared_ptr readImage() override; @@ -45,10 +45,10 @@ class MVImpactDriver : public CameraDriver { float getGamma() override; void setGamma(float gamma) override; - WhiteBalanceType getWhiteBalanceType() override; + SSL_VPConfigCameraWBType getWhiteBalanceType() override; float getWhiteBalanceBlue() override; float getWhiteBalanceRed() override; - void setWhiteBalance(WhiteBalanceType type, float blue, float red) override; + void setWhiteBalance(SSL_VPConfigCameraWBType type, float blue, float red) override; private: mvIMPACT::acquire::Device* device; diff --git a/src/driver/opencvdriver.cpp b/src/driver/opencvdriver.cpp index 4a63cb3..0899dbe 100644 --- a/src/driver/opencvdriver.cpp +++ b/src/driver/opencvdriver.cpp @@ -23,12 +23,12 @@ static constexpr double OPENCV_AUTO_EXPOSURE_ON = 0.75; static constexpr double OPENCV_AUTO_EXPOSURE_OFF = 0.25; -OpenCVDriver::OpenCVDriver(const CameraConfig& config): capture(config.device, cv::CAP_ANY, {cv::CAP_PROP_HW_ACCELERATION, cv::VIDEO_ACCELERATION_ANY}), name(config.device) { +OpenCVDriver::OpenCVDriver(std::string path): capture(path, cv::CAP_ANY, {cv::CAP_PROP_HW_ACCELERATION, cv::VIDEO_ACCELERATION_ANY}), name(path) { std::replace(name.begin(), name.end(), '/', '_'); // Usually a wrong path or a camera busy in another program; later calls would throw. if(!capture.isOpened()) - FATAL("Could not open camera " << config.device << ": no OpenCV backend can open it. Check the path, and whether another program is using the camera (fuser -v " << config.device << ")."); + FATAL("Could not open camera " << path << ": no OpenCV backend can open it. Check the path, and whether another program is using the camera (fuser -v " << path << ")."); // Use compressed data stream to unlock the highest resolution - framerate combination on USB2 cameras capture.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('M', 'J', 'P', 'G')); @@ -143,11 +143,11 @@ void OpenCVDriver::setGamma(float gamma) { capture.set(cv::CAP_PROP_GAMMA, gamma); } -WhiteBalanceType OpenCVDriver::getWhiteBalanceType() { +SSL_VPConfigCameraWBType OpenCVDriver::getWhiteBalanceType() { if(capture.get(cv::CAP_PROP_AUTO_WB) == 1.0) { - return WhiteBalanceType::WhiteBalanceType_AutoOutdoor; + return OUTDOOR; } else { - return WhiteBalanceType::WhiteBalanceType_Manual; + return MANUAL; } } @@ -159,8 +159,8 @@ float OpenCVDriver::getWhiteBalanceRed() { return (float)capture.get(cv::CAP_PROP_WHITE_BALANCE_RED_V); } -void OpenCVDriver::setWhiteBalance(WhiteBalanceType type, float blue, float red) { - if(type != WhiteBalanceType::WhiteBalanceType_Manual) { +void OpenCVDriver::setWhiteBalance(SSL_VPConfigCameraWBType type, float blue, float red) { + if(type != MANUAL) { capture.set(cv::CAP_PROP_AUTO_WB, 1.0); } else { capture.set(cv::CAP_PROP_AUTO_WB, 0.0); diff --git a/src/driver/opencvdriver.h b/src/driver/opencvdriver.h index 8abd398..a3dc3c1 100644 --- a/src/driver/opencvdriver.h +++ b/src/driver/opencvdriver.h @@ -21,7 +21,7 @@ class OpenCVDriver : public CameraDriver { public: - explicit OpenCVDriver(const CameraConfig& config); + explicit OpenCVDriver(std::string path); std::shared_ptr readImage() override; @@ -44,10 +44,10 @@ class OpenCVDriver : public CameraDriver { float getGamma() override; void setGamma(float gamma) override; - WhiteBalanceType getWhiteBalanceType() override; + SSL_VPConfigCameraWBType getWhiteBalanceType() override; float getWhiteBalanceBlue() override; float getWhiteBalanceRed() override; - void setWhiteBalance(WhiteBalanceType type, float blue, float red) override; + void setWhiteBalance(SSL_VPConfigCameraWBType type, float blue, float red) override; private: void applyExposure(); diff --git a/src/driver/spinnakerdriver.cpp b/src/driver/spinnakerdriver.cpp index b5ce7b4..f9b77cd 100644 --- a/src/driver/spinnakerdriver.cpp +++ b/src/driver/spinnakerdriver.cpp @@ -106,13 +106,13 @@ class SpinnakerImage : public RawImage { }; // Function try block: unexpected camera errors during setup exit with a clear message -SpinnakerDriver::SpinnakerDriver(const CameraConfig& config) try { +SpinnakerDriver::SpinnakerDriver(const std::string& device, uint32_t hardwareId) try { pSystem = Spinnaker::System::GetInstance(); - const std::string camera = config.device.empty() ? "id " + std::to_string(config.hardwareId) : "with serial " + config.device; + const std::string camera = device.empty() ? "id " + std::to_string(hardwareId) : "with serial " + device; while(true) { Spinnaker::CameraList camList = pSystem->GetCameras(); - pCam = config.device.empty() ? getBySerialOrder(camList, config.hardwareId) : camList.GetBySerial(config.device); + pCam = device.empty() ? getBySerialOrder(camList, hardwareId) : camList.GetBySerial(device); if (!pCam.IsValid()) { WARN("Waiting for camera " << camera << ", found " << camList.GetSize() << " camera(s)"); } else { @@ -436,15 +436,15 @@ void SpinnakerDriver::setGamma(float gamma) { } } -WhiteBalanceType SpinnakerDriver::getWhiteBalanceType() { +SSL_VPConfigCameraWBType SpinnakerDriver::getWhiteBalanceType() { if(pCam->BalanceWhiteAuto.GetValue() == Spinnaker::BalanceWhiteAuto_Off) { - return WhiteBalanceType::WhiteBalanceType_Manual; + return MANUAL; } else if(!IsReadable(pCam->BalanceWhiteAutoProfile)) { return whiteBalanceType; // First generation cameras have a single auto profile } else { return (pCam->BalanceWhiteAutoProfile.GetValue() == Spinnaker::BalanceWhiteAutoProfile_Outdoor) - ? WhiteBalanceType::WhiteBalanceType_AutoOutdoor - : WhiteBalanceType::WhiteBalanceType_AutoIndoor; + ? OUTDOOR + : INDOOR; } } @@ -458,12 +458,12 @@ float SpinnakerDriver::getWhiteBalanceRed() { return pCam->BalanceRatio.GetValue(); } -void SpinnakerDriver::setWhiteBalance(WhiteBalanceType type, float blue, float red) { - if(type != WhiteBalanceType_Manual) { +void SpinnakerDriver::setWhiteBalance(SSL_VPConfigCameraWBType type, float blue, float red) { + if(type != MANUAL) { whiteBalanceType = type; CATCH_SPINNAKER(pCam->BalanceWhiteAuto.SetValue(Spinnaker::BalanceWhiteAuto_Continuous)); setOptional(pCam->BalanceWhiteAutoProfile, - type == WhiteBalanceType_AutoOutdoor + type == OUTDOOR ? Spinnaker::BalanceWhiteAutoProfile_Outdoor : Spinnaker::BalanceWhiteAutoProfile_Indoor, "auto white balance profile"); diff --git a/src/driver/spinnakerdriver.h b/src/driver/spinnakerdriver.h index a9af509..6662375 100644 --- a/src/driver/spinnakerdriver.h +++ b/src/driver/spinnakerdriver.h @@ -25,7 +25,7 @@ class SpinnakerDriver : public CameraDriver { public: - explicit SpinnakerDriver(const CameraConfig& config); + explicit SpinnakerDriver(const std::string& device, uint32_t hardwareId); ~SpinnakerDriver() override; std::shared_ptr readImage() override; @@ -50,10 +50,10 @@ class SpinnakerDriver : public CameraDriver { float getGamma() override; void setGamma(float gamma) override; - WhiteBalanceType getWhiteBalanceType() override; + SSL_VPConfigCameraWBType getWhiteBalanceType() override; float getWhiteBalanceBlue() override; float getWhiteBalanceRed() override; - void setWhiteBalance(WhiteBalanceType type, float blue, float red) override; + void setWhiteBalance(SSL_VPConfigCameraWBType type, float blue, float red) override; private: void loadDefaultUserSet(); @@ -67,7 +67,7 @@ class SpinnakerDriver : public CameraDriver { const PixelFormat* pixelFormat = &PixelFormat::RGGB8; // Last requested auto profile, reported back on cameras without BalanceWhiteAutoProfile - WhiteBalanceType whiteBalanceType = WhiteBalanceType_AutoOutdoor; + SSL_VPConfigCameraWBType whiteBalanceType = OUTDOOR; // Cached so the frame loop doesn't do a register read (a network round trip on GigE) every frame bool autoExposure = false; diff --git a/src/geometry_benchmark.cpp b/src/geometry_benchmark.cpp index e2e3e55..cded728 100644 --- a/src/geometry_benchmark.cpp +++ b/src/geometry_benchmark.cpp @@ -16,10 +16,12 @@ #include #include #include "Resources.h" +#include "driver/cameradriver.h" #include "GroundTruth.h" #include "proto/vision/ssl_vision_wrapper.pb.h" #include "calib/LineDetection.h" #include "calib/GeomModel.h" +#include "config.h" static void moveRobot(const Resources& r, SSL_DetectionRobot& robot) { Eigen::Vector3f pos = r.perspective->model.image2field({robot.pixel_x(), robot.pixel_y()}, robot.height()); @@ -45,7 +47,7 @@ static void geometryBenchmark(Resources& r, const uint32_t frameId) { ball.set_y(pos.y()); } - detection->set_camera_id(r.camId); + detection->set_camera_id(config.camera_id()); detection->set_t_capture(getRealTime()); detection->set_t_sent(getRealTime()); r.socket->send(wrapper); @@ -54,7 +56,7 @@ static void geometryBenchmark(Resources& r, const uint32_t frameId) { int main(int argc, char* argv[]) { Resources r(argc > 1 ? argv[1] : "config.yml"); - std::shared_ptr img = r.camera->readImage(); + std::shared_ptr img = camera->readImage(); r.perspective->geometryCheck(img->width, img->height, r.gcSocket->maxBotHeight, r.resamplingFactor); std::shared_ptr channels[4]; r.raw2quad(*img, channels); diff --git a/src/main.cpp b/src/main.cpp index 97a5bd4..df1a1ce 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -14,6 +14,7 @@ limitations under the License. */ #include +#include "driver/cameradriver.h" #include "log.h" #include #include @@ -31,6 +32,15 @@ #include "blobs/colorupdate.h" #include +/* Maximum amount of blobs processed per frame. */ +#define MAX_BLOBS 2000 + +/* Expect robots to move at least this many mm between frames. */ +#define MIN_BOT_TRACKING_RADIUS 20.0f + +/* Maximum expected robot acceleration between frames in mm/s². */ +#define MAX_BOT_ACCELERATION 6500.0f + struct __attribute__ ((packed)) CLMatch { float x, y; RGB color; @@ -94,7 +104,7 @@ void generateRadiusSearchTrackedBotHypotheses(const Resources& r, std::list bestBot = nullptr; @@ -172,7 +182,7 @@ static inline bool closerThanCamEdgeDistance(const Resources& r, const Eigen::Ve // Don't filter if border is outside field -> cannot be a partial robot bool borderInsideField = borderPos.x() >= -halfFieldLength && borderPos.x() <= halfFieldLength && borderPos.y() >= -halfFieldWidth && borderPos.y() <= halfFieldWidth; - return borderInsideField && (borderPos - pos).squaredNorm() < r.minCamEdgeDistance*r.minCamEdgeDistance; + return borderInsideField && (borderPos - pos).squaredNorm() < config.thresholds().min_cam_edge_distance()*config.thresholds().min_cam_edge_distance(); } void filterBallsAtCamEdge(const Resources& r, std::list>& balls) { @@ -252,12 +262,14 @@ void sig_stop(int sig_num) { int main(int argc, char* argv[]) { init_config(argc > 1 ? argv[1] : "config.yml"); Resources r(argc > 1 ? argv[1] : "config.yml"); + init_camera(); + update_camera_config(&config.camera()); cl::Kernel blobList = r.openCl->compile(kernel_blobList_cl); uint32_t frameId = 0; double lastConfigSendTime = 0.0; double lastDebugSaveTime = 0.0; - CLArray matchArray(sizeof(CLMatch) * r.maxBlobs); + CLArray matchArray(sizeof(CLMatch) * MAX_BLOBS); CLArray counter(sizeof(cl_int)*3); signal(SIGTERM, sig_stop); @@ -265,11 +277,12 @@ int main(int argc, char* argv[]) { while(noSigterm) { frameId++; r.reloadConfigIfChanged(); - std::shared_ptr img = r.camera->readImage(); + apply_received_config(r); + std::shared_ptr img = camera->readImage(); if(img == nullptr) break; - double startTime = r.camera->getTime(); + double startTime = camera->getTime(); double realStartTime = getRealTime(); // Just for realtime performance measurements r.socket->geometryCheck(); @@ -289,7 +302,7 @@ int main(int argc, char* argv[]) { counterMap[1] = 0; counterMap[2] = 0; } - r.openCl->await(blobList, cl::EnqueueArgs(cl::NDRange(r.perspective->reprojectedFieldSize[0], r.perspective->reprojectedFieldSize[1])), flat->image, blobCenter->image, matchArray.buffer, counter.buffer, (float)r.minCircularity, (float)0.0f, (int)floorf(r.perspective->minBlobRadius / r.perspective->fieldScale), r.maxBlobs); + r.openCl->await(blobList, cl::EnqueueArgs(cl::NDRange(r.perspective->reprojectedFieldSize[0], r.perspective->reprojectedFieldSize[1])), flat->image, blobCenter->image, matchArray.buffer, counter.buffer, config.thresholds().circularity(), (float)0.0f, (int)floorf(r.perspective->minBlobRadius / r.perspective->fieldScale), MAX_BLOBS); if(r.debugImages && frameId == 1) { flat->save(".flat." + std::to_string(frameId) + ".png"); @@ -301,7 +314,7 @@ int main(int argc, char* argv[]) { { CLMap counterMap = counter.read(); CLMap matchMap = matchArray.read(); - const int matchAmount = std::min(r.maxBlobs, counterMap[0]); + const int matchAmount = std::min(MAX_BLOBS, counterMap[0]); matches.reserve(matchAmount); for(int i = 0; i < matchAmount; i++) { @@ -315,8 +328,8 @@ int main(int argc, char* argv[]) { }); } - if(counterMap[0] > r.maxBlobs) - WARN("max blob amount reached: " << counterMap[0] << "/" << r.maxBlobs); + if(counterMap[0] > MAX_BLOBS) + WARN("max blob amount reached: " << counterMap[0] << "/" << MAX_BLOBS); } std::list> botHypotheses; @@ -329,7 +342,7 @@ int main(int argc, char* argv[]) { generateRadiusSearchTrackedBotHypotheses(r, botHypotheses, matches, blobs, startTime); generateAngleSortedBotHypotheses(r, botHypotheses, matches, blobs); - filterHypothesesScore(botHypotheses, r.minConfidence); + filterHypothesesScore(botHypotheses, config.thresholds().min_confidence()); filterClippingBotBotHypotheses(r, botHypotheses); generateNonclippingBallHypotheses(r, botHypotheses, matches, ballHypotheses); } @@ -340,9 +353,9 @@ int main(int argc, char* argv[]) { for (auto& ball : ballHypotheses) ball->recalcPostColorCalib(r); - filterHypothesesScore(ballHypotheses, r.minConfidence); + filterHypothesesScore(ballHypotheses, config.thresholds().min_confidence()); filterBallsAtCamEdge(r, ballHypotheses); - filterStddevScore(ballHypotheses, (float)r.minScore); + filterStddevScore(ballHypotheses, config.thresholds().score()); SSL_WrapperPacket wrapper; wrapper.set_source(SSL_SOURCE_VISION_PROCESSOR); @@ -351,7 +364,7 @@ int main(int argc, char* argv[]) { detection->set_t_capture(startTime); if(img->timestamp != 0) detection->set_t_capture_camera(img->timestamp); - detection->set_camera_id(r.camId); + detection->set_camera_id(config.camera_id()); for (const auto& bot : botHypotheses) bot->addToDetectionFrame(r, detection); @@ -368,36 +381,32 @@ int main(int argc, char* argv[]) { VP_LOG("time " << processingTime * 1000.0 << " ms " << matches.size() << " blobs " << detection->balls().size() << " balls " << (detection->robots_yellow_size() + detection->robots_blue_size()) << " bots"); r.openCl->printRuntimes(); #else - detection->set_t_sent(r.camera->getTime()); + detection->set_t_sent(camera->getTime()); #endif r.socket->send(wrapper); r.socket->updateTime(); r.openCl->clearEvents(); - if(processingTime > r.camera->expectedFrametime()) + if(processingTime > camera->expectedFrametime()) VP_LOG("frame time overrun: " << processingTime * 1000.0 << " ms " << matches.size() << " blobs " << detection->balls().size() << " balls " << (detection->robots_yellow_size() + detection->robots_blue_size()) << " bots"); - if(r.rawFeed) { - r.streamQuad(channels); - } else { - switch(((long)(startTime/20.0) % 4)) { - case 0: - r.streamQuad(channels); - break; - case 1: - r.streamImage(*flat); - break; - case 2: - r.streamImage(*gradDot); - break; - case 3: - r.streamImage(*blobCenter); - break; - } + switch(config.stream().type()) { + case RAW: + r.streamQuad(channels); + break; + case REPROJ_FALSE_COLOR: + r.streamImage(*flat); + break; + case REPROJ_GRADIENT_DOT: + r.streamImage(*gradDot); + break; + case REPROJ_BLOB_SCORE: + r.streamImage(*blobCenter); + break; } if(r.debugStreamIntervalMs > 0 && (realStartTime - lastDebugSaveTime) * 1000.0 >= r.debugStreamIntervalMs) { - const std::string prefix = "img/" + std::to_string(r.camId) + "."; + const std::string prefix = "img/" + std::to_string(config.camera_id()) + "."; r.snapshotWriter->offer(r.quad2rgba(channels), prefix + "raw.jpg"); r.snapshotWriter->offer(flat, prefix + "flat.jpg"); r.snapshotWriter->offer(gradDot, prefix + "gradient.jpg"); @@ -409,7 +418,7 @@ int main(int argc, char* argv[]) { geometryCalibration(r, *rgba); if(r.debugStreamIntervalMs > 0 && (realStartTime - lastDebugSaveTime) * 1000.0 >= r.debugStreamIntervalMs) { - r.snapshotWriter->offer(rgba, "img/" + std::to_string(r.camId) + ".raw.jpg"); + r.snapshotWriter->offer(rgba, "img/" + std::to_string(config.camera_id()) + ".raw.jpg"); lastDebugSaveTime = realStartTime; } } else { @@ -417,7 +426,7 @@ int main(int argc, char* argv[]) { bool periodicSave = r.debugStreamIntervalMs > 0 && (realStartTime - lastDebugSaveTime) * 1000.0 >= r.debugStreamIntervalMs; if(frameId == 100 || periodicSave) { // Wait for automatic gain, exposure and white balance adjustments - r.snapshotWriter->offer(r.quad2rgba(channels), "img/" + std::to_string(r.camId) + ".raw.jpg"); + r.snapshotWriter->offer(r.quad2rgba(channels), "img/" + std::to_string(config.camera_id()) + ".raw.jpg"); lastDebugSaveTime = realStartTime; if(frameId == 100) VP_LOG("Saved sample image"); diff --git a/src/rtpstreamer.cpp b/src/rtpstreamer.cpp index 00da74f..4cdd304 100644 --- a/src/rtpstreamer.cpp +++ b/src/rtpstreamer.cpp @@ -15,6 +15,9 @@ */ #include "rtpstreamer.h" #include "log.h" +#include "config.h" +#include +#include extern "C" { #include @@ -24,8 +27,14 @@ extern "C" { #include } +RTPStreamer rtpStreamer; // TODO false, "rtp://224.5.23.100:10100" -RTPStreamer::RTPStreamer(bool active, std::string uri, int framerate): active(active), uri(std::move(uri)), framerate(framerate), frametime_us(1000000 / framerate) { +void update_stream_config(const SSL_VPConfigStream* stream_config) { + +} + + +RTPStreamer::RTPStreamer(): frametime_us(1000000 / framerate) { encoder = std::thread(&RTPStreamer::encoderRun, this); } @@ -41,9 +50,16 @@ RTPStreamer::~RTPStreamer() { freeResources(); } +void RTPStreamer::updateConfig(const SSL_VPConfigStream& stream_config) { + config.mutable_stream()->MergeFrom(stream_config); + + std::unique_lock lock(configMutex); + pendingConfig.CopyFrom(config.stream()); +} + //Adopted from CC BY-SA 4.0 https://stackoverflow.com/a/61988145 Dmitrii Zabotlin void RTPStreamer::sendFrame(std::shared_ptr image) { - if(!active) + if(!pendingConfig.active()) // Mutex not needed as update only happens on the same thread return; std::unique_lock lock(queueMutex); @@ -164,10 +180,17 @@ void RTPStreamer::encoderRun() { queue = nullptr; } - if(image->width != width || image->height != height) { + std::string cfgUri; + { + std::unique_lock lock(configMutex); + cfgUri = "rtp://" + pendingConfig.stream_ip() + ":" + std::to_string(pendingConfig.stream_port()); + } + + if(uri != cfgUri || image->width != width || image->height != height) { freeResources(); width = image->width; height = image->height; + uri = cfgUri; } allocResources(); diff --git a/src/rtpstreamer.h b/src/rtpstreamer.h index 47a0362..c2648bf 100644 --- a/src/rtpstreamer.h +++ b/src/rtpstreamer.h @@ -22,6 +22,7 @@ #include #include "opencl.h" +#include "vision/ssl_vp_config.pb.h" typedef struct AVCodec AVCodec; @@ -34,19 +35,22 @@ typedef struct AVPacket AVPacket; class RTPStreamer { public: - explicit RTPStreamer(bool active, std::string uri, int framerate = 30); + explicit RTPStreamer(); ~RTPStreamer(); void sendFrame(std::shared_ptr image); + void updateConfig(const SSL_VPConfigStream& stream_config); private: void encoderRun(); void allocResources(); void freeResources(); - const bool active; - const std::string uri; - const int framerate; + std::mutex configMutex = std::mutex(); + SSL_VPConfigStream pendingConfig; + + const int framerate = 30; const int frametime_us; + std::string uri = "rtp://127.0.0.1:10100"; int width = 0; int height = 0; @@ -64,3 +68,5 @@ class RTPStreamer { AVFrame* frame = nullptr; AVPacket* pkt = nullptr; }; + +extern RTPStreamer rtpStreamer; diff --git a/src/udpsocket.cpp b/src/udpsocket.cpp index 77f57e2..7da2d19 100644 --- a/src/udpsocket.cpp +++ b/src/udpsocket.cpp @@ -17,9 +17,11 @@ #include "proto/vision/ssl_vision_wrapper.pb.h" #include "proto/gamecontroller/ssl_gc_referee_message.pb.h" #include "driver/cameradriver.h" +#include "config.h" #include #include "log.h" +#include "proto/vision/ssl_vp_config.pb.h" #include #include #include @@ -126,6 +128,7 @@ void VisionSocket::geometryCheck() { geometryVersion++; VP_LOG("New geometry received"); } + camId = config.camera_id(); geometryMutex.unlock(); } @@ -143,6 +146,14 @@ std::vector VisionSocket::getReceivedOffsets() { return copy; } +SSL_VPConfig VisionSocket::getReceivedConfig() { + SSL_VPConfig result; + configMutex.lock(); + result.CopyFrom(receivedConfig); + configMutex.unlock(); + return result; +} + void VisionSocket::parse(char *data, int length) { SSL_WrapperPacket wrapper; @@ -160,6 +171,12 @@ void VisionSocket::parse(char *data, int length) { geometryMutex.unlock(); } } + + if(wrapper.has_config() && config.instance() == wrapper.config().instance()) { + configMutex.lock(); + receivedConfig.CopyFrom(wrapper.config()); + configMutex.unlock(); + } } static void trackBots(const double timestamp, const float defaultBotHeight, const google::protobuf::RepeatedPtrField& bots, const std::vector& previous, std::vector& objects, int idOffset) { diff --git a/src/udpsocket.h b/src/udpsocket.h index ee8b056..72049d5 100644 --- a/src/udpsocket.h +++ b/src/udpsocket.h @@ -21,6 +21,7 @@ #include #include "proto/vision/ssl_vision_geometry.pb.h" #include "proto/vision/ssl_vision_detection.pb.h" +#include "vision/ssl_vp_config.pb.h" #ifdef _WIN32 #include // before Windows.h, else Winsock 1 conflict @@ -67,13 +68,15 @@ struct TrackingState { /** Socket handling vision messages. */ class VisionSocket: public UDPSocket { public: - VisionSocket(const std::string &ip, uint16_t port, int camId, float defaultBotHeight): UDPSocket(ip, port), camId(camId), defaultBotHeight(defaultBotHeight) {} + VisionSocket(const std::string &ip, uint16_t port, float defaultBotHeight): UDPSocket(ip, port), camId(camId), defaultBotHeight(defaultBotHeight) {} /** Check if a new geometry update has been received and update geometry and geometryVersion accordingly. */ void geometryCheck(); int getGeometryVersion() const { return geometryVersion; } SSL_GeometryData& getGeometry() { return geometry; } + SSL_VPConfig getReceivedConfig(); + std::map> getTrackedObjects(); /** Update the clock time offset. */ @@ -88,7 +91,7 @@ class VisionSocket: public UDPSocket { void timeSynchronization(const SSL_DetectionFrame& detection); /** Camera id of this socket. */ - const int camId; + int camId = 0; /** Default bot height to be used if the bot height is missing from received detection frames. */ const float defaultBotHeight; @@ -101,6 +104,9 @@ class VisionSocket: public UDPSocket { /** Last received geometry, should only be accessed when having geometryMutex locked. */ SSL_GeometryData receivedGeometry; std::mutex geometryMutex; + /** Last received config, only to be accessed with configMutex lock. */ + SSL_VPConfig receivedConfig; + std::mutex configMutex; /** Currently tracked objects. Should only be accessed when having trackedMutex locked. */ std::map> trackedObjects;