|
| 1 | +// Copyright 2024 TIER IV, Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#include "perception_utils/run_length_encoder.hpp" |
| 16 | + |
| 17 | +namespace perception_utils |
| 18 | +{ |
| 19 | + |
| 20 | +std::vector<std::pair<uint8_t, int>> runLengthEncoder(const cv::Mat & image) |
| 21 | +{ |
| 22 | + std::vector<std::pair<uint8_t, int>> compressed_data; |
| 23 | + const int rows = image.rows; |
| 24 | + const int cols = image.cols; |
| 25 | + compressed_data.emplace_back(image.at<uint8_t>(0, 0), 0); |
| 26 | + for (int i = 0; i < rows; ++i) { |
| 27 | + for (int j = 0; j < cols; ++j) { |
| 28 | + uint8_t current_value = image.at<uint8_t>(i, j); |
| 29 | + if (compressed_data.back().first == current_value) { |
| 30 | + ++compressed_data.back().second; |
| 31 | + } else { |
| 32 | + compressed_data.emplace_back(current_value, 1); |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + return compressed_data; |
| 37 | +} |
| 38 | + |
| 39 | +cv::Mat runLengthDecoder(const std::vector<uint8_t> & rle_data, const int rows, const int cols) |
| 40 | +{ |
| 41 | + cv::Mat mask(rows, cols, CV_8UC1, cv::Scalar(0)); |
| 42 | + int idx = 0; |
| 43 | + int step = sizeof(uint8_t) + sizeof(int); |
| 44 | + for (size_t i = 0; i < rle_data.size(); i += step) { |
| 45 | + uint8_t value; |
| 46 | + int length; |
| 47 | + std::memcpy(&value, &rle_data[i], sizeof(uint8_t)); |
| 48 | + std::memcpy( |
| 49 | + &length, &rle_data[i + 1], |
| 50 | + sizeof( |
| 51 | + int)); // under the condition that we know rle_data[i] only consume 1 element of the vector |
| 52 | + for (int j = 0; j < length; ++j) { |
| 53 | + int row_idx = static_cast<int>(idx / cols); |
| 54 | + int col_idx = static_cast<int>(idx % cols); |
| 55 | + mask.at<uint8_t>(row_idx, col_idx) = value; |
| 56 | + idx++; |
| 57 | + if (idx > rows * cols) { |
| 58 | + break; |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + return mask; |
| 63 | +} |
| 64 | + |
| 65 | +} // namespace perception_utils |
0 commit comments