Files
Capstone_Design/ch11/thershhold/main.cpp
2025-04-30 12:11:45 +09:00

54 lines
1.3 KiB
C++

#include <iostream>
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
void on_trackbar(int pos, void* userdata);
int main(int argc, char* argv[]) {
Mat src;
if (argc < 2)
src = imread("../../resources/images/neutrophils.png", IMREAD_GRAYSCALE);
else
src = imread(argv[1], IMREAD_GRAYSCALE);
if (src.empty()) {
cerr << "Image load failed!" << endl;
return -1;
}
namedWindow("dst");
createTrackbar("Threshold", "dst", 0, 255, on_trackbar, (void*)&src);
setTrackbarPos("Threshold", "dst", 128);
cv::waitKey();
cv::destroyAllWindows();
}
void on_trackbar(int pos, void* userdata) {
Mat src = *(Mat*)userdata;
Mat hist;
int channels[] = { 0 };
int dims = 1;
const int histSize[] = { 256 };
float graylevel[] = { 0, 256 };
const float* ranges[] = { graylevel };
calcHist(&src, 1, channels, noArray(), hist, dims, histSize, ranges);
double histMax;
minMaxLoc(hist, 0, &histMax);
Mat imgHist(100, 256, CV_8UC1, Scalar(255));
for (int i = 0; i < 256; i++) {
line(imgHist, Point(i, 100), Point(i, 100 - cvRound(hist.at<float>(i, 0) * 100 / histMax)), Scalar(0));
}
line(imgHist, Point(pos, 0), Point(pos, 100), 0, 1, LINE_AA);
Mat dst;
threshold(src, dst, pos, 255, THRESH_BINARY);
imshow("dst", dst);
imshow("hist", imgHist);
}