gpt4 book ai didi

c++ - 如何为二进制图像中的形状重新着色以进行索引(填充)?

转载 作者:行者123 更新时间:2023-12-01 15:10:43 28 4
gpt4 key购买 nike

我创建了带有阈值的二进制图像。如下图所示如何改变白色形状的颜色以使其可索引?

到目前为止,这是我的代码:

void threshold()
{
cv::Mat src_8uc3_img = cv::imread("images/train.png", CV_LOAD_IMAGE_GRAYSCALE); // load color image from file system to Mat variable, this will be loaded using 8 bits (uchar)

if (src_8uc3_img.empty()) {
printf("Unable to read input file (%s, %d).", __FILE__, __LINE__);
}

double thresh = 0;
double maxValue = 255;

cv::Mat thresh_holding = src_8uc3_img.clone();
cv::Mat indexing = src_8uc3_img.clone();
cv::imshow("Train", src_8uc3_img);

for (int y = 0; y < thresh_holding.rows ; y++) {
for (int x = 0; x < thresh_holding.cols ; x++) {
uchar thX = thresh_holding.at<uchar>(y, x);
if (thX < 128 ) {
thresh_holding.at<uchar>(y, x) = thresh;
}
else if (thX>128){
thresh_holding.at<uchar>(y, x) = maxValue;
}
}
}

cv::imshow("ThreshHolding", thresh_holding);

cv::waitKey(0); // wait until keypressed

}

最佳答案

首先,它是“阈值”,而不是“阈值保持”。这意味着设置/应用阈值,而不意味着保持阈值。

您想要的显然是找到图像的connected components。除非您想学习基本的图像处理,否则首先要使用 threshold() 函数。然后不要使用findContours() / drawContours() ,因为它们很慢。如果要使用不同的连接组件,请使用 connectedComponents() :速度很快,并且每个组件都有一个不同的标签。根据索引,颜色取决于您。

受Alex Alex Python答案的启发,您可以在此处找到C++版本:

#include <opencv2/opencv.hpp>

int main(void)
{
using namespace cv;
// Read image
Mat1b img = imread("input.png", IMREAD_GRAYSCALE);
// Make sure it's binary
threshold(img, img, 128, 255, THRESH_BINARY);
// Extract connected components
Mat1i labels;
int nlabels = connectedComponents(img, labels);
// Make the connected components from 0 to 255 (assume less than 256 labels)
img = labels * 255 / nlabels;
// Make the labels colored
Mat3b colored, output;
applyColorMap(img, colored, COLORMAP_JET);
// Mask background with zeros in original image
colored.copyTo(output, img);
// Write output
imwrite("output.png", output);
}

唯一的区别是,我为图像指定了类型,以便将 img的分配也转换为8 bpp。输入的 Mat更好用。

关于c++ - 如何为二进制图像中的形状重新着色以进行索引(填充)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61501775/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com