OpenCVでの代入
いい感じに処理してくれるところとそうでないところが混ざっているため、少しわかりにくいです。今回は型違いの代入についてメモ。
# include <iostream>
# include <opencv2/core/core.hpp>
int main(void) {
cv::Mat matdouble = (cv::Mat_<double>(3, 3) << 2, 2, 3, 4, 5, 6, 7, 8, 9);
std::cout << "matdouble:" << std::endl << matdouble << std::endl << std::endl;
// 違う型のMatにキャストしながら代入する
cv::Mat matuchar = (cv::Mat_<uchar>(3, 3) << 1, 1, 1, 1, 1, 1, 1, 1, 1);
// 只の代入ではうまく行っているように見えて、データごとには間違っている
matuchar = matdouble;
std::cout << std::endl << "matuchar:" << std::endl << matuchar << std::endl << std::endl;
std::cout << "matuchar[0]:" << (double)matuchar.data[0] << std::endl; // matuchar[0]: 0
// こちらが正しい
matdouble.convertTo(matuchar, CV_8UC1); //CV_8UC1: 8bit unsigned char channel 1
std::cout << std::endl << "matuchar:" << std::endl << matuchar << std::endl << std::endl;
std::cout << "matuchar[0]:" << (double)matuchar.data[0] << std::endl; // matucahr[0]: 2
return 0;
}