[英]Convert OpenCV Mat into a "bitmask"
我目前正在使用 openCV 來獲取一些 ascii 字符的位掩碼。
為此,我使用以下代碼:
// some includes might be useless in this example
#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
int main() {
cv::Mat tmp = cv::Mat(64, 64, CV_8UC3, cv::Scalar(0, 0, 0));
cv::putText(tmp,
".",
cv::Point(31, 31),
cv::FONT_HERSHEY_PLAIN,
1,
CV_RGB(255, 255, 255)
);
for (int y = 0; y < tmp.size().height; y++) {
for (int x = 0; x < tmp.size().width; x++) {
uchar val = tmp.at<uchar>(y,x);
// if (val == 0)
// printf(" ");
// else
// printf("\e[47m \e[0m");
printf("%d,", val);
}
// printf("|\n");
printf("\n");
}
for (;;) {
cv::imshow("Dot", tmp);
if (cv::waitKey(16) >= 0)
break;
};
}
由此我希望在標准輸出上看到一個 64*64 的正方形,其中填充了很多 0(代表黑色像素)和一些 255(代表白色像素),其中白色像素會形成一個點。
但是生成的 output 是 64*64 正方形,只有 0。
我真的不明白我做錯了什么。
我也嘗試使用tmp.data
而不是tmp.at
但結果是一樣的。 當我嘗試從tmp.data
迭代到tmp.dataend
這也不起作用(這次我有更多的 0 但仍然沒有 255)
忘了提到,最終目標是將圖像存儲為uint8_t *
的數組,所以如果我可以直接獲得uint8_t *
而無需經過 1000 步,我也會接受幫助
總的來說,任何幫助將不勝感激。 提前致謝
盡管評論指出您需要一個通道圖像(CV_8UC1)而不是三個通道。 您或其他人可能想知道為什么上面的代碼不能按預期工作。
查看Mat::at()
的源代碼,您會發現 memory 地址其結果取決於模板參數。 例如,如果tmp.data
是0x55ed6bb8d1c0
,那么:
tmp.at<uchar>(30, 31)
位於0x55ed6bb8e85f
,來自tmp.data
的5791 (30*64*3+31) 字節tmp.at<Vec3b>(30, 31)
位於0x55ed6bb8e89d
,來自tmp.data
的5853 (30*64*3+31*3) 字節您上面的代碼永遠無法讀取值為{255, 255, 255}
的像素。 這就是為什么它只有 output 0
。
使用uchar val = tmp.at<Vec3b>(y, x)[0];
可以使它工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.