OpenCV 4.12.0
开源计算机视觉
加载中...
搜索中...
无匹配项
创建 3D 直方图

上一个教程: 创建小部件

目标

在本教程中,您将学习如何

  • 为 viz 窗口创建自己的回调键盘函数。
  • 在 viz 窗口中显示你的3D直方图。

代码

你可以从这里下载代码。

#include <opencv2/core.hpp>
#include <iostream>
using namespace std;
using namespace cv;
#ifdef HAVE_OPENCV_VIZ
#include <opencv2/viz.hpp>
const String keys =
"{Aide h usage ? help | | print this message }"
"{@arg1 | | Full path to color imag (3 channels)}"
;
struct Histo3DData {
Mat histogram;
int seuil;
double threshold;
int nbWidget;
bool status;
double maxH;
int code;
};
void DrawHistogram3D(Histo3DData &);
void AddSlidebar(String sliderName, String windowName, int sliderMin, int sliderMax, int valeurDefaut, int *sliderVal, void(*f)(int, void *), void *r);
void UpdateThreshold(int , void * r);
void KeyboardViz3d(const viz::KeyboardEvent &w, void *t);
void DrawHistogram3D(Histo3DData &h)
{
int planSize = (int)h.histogram.step1(0);
int cols = (int)h.histogram.step1(1);
int rows = (int)planSize / cols;
int plans = (int)h.histogram.total() / planSize;
h.fen3D->removeAllWidgets();
h.nbWidget=0;
if (h.nbWidget==0)
h.fen3D->showWidget("Axis", viz::WCoordinateSystem(10));
for (int k = 0; k < plans; k++)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
double x = h.histogram.at<float>(k, i, j);
if (x >= h.threshold)
{
double r=std::max(x/h.maxH,0.1);
viz::WCube s(Point3d(k - r / 2, i - r / 2, j - r / 2), Point3d(k + r / 2, i + r / 2, j + r / 2), false, viz::Color(j / double(plans) * 255, i / double(rows) * 255, k / double(cols) * 255));
h.fen3D->showWidget(format("I3d%d", h.nbWidget++), s);
}
}
}
}
h.status = false;
}
void KeyboardViz3d(const viz::KeyboardEvent &w, void *t)
{
Histo3DData *x=(Histo3DData *)t;
if (w.action)
cout << "你按下了 "<< w.symbol<< " 在 viz 窗口 "<<x->fen3D->getWindowName()<<"\n";
x->code= w.code;
switch (w.code) {
case '/'
x->status=true;
x->threshold *= 0.9;
break;
case '*'
x->status = true;
x->threshold *= 1.1;
break;
}
if (x->status)
{
cout << x->threshold << "\n";
DrawHistogram3D(*x);
}
}
void AddSlidebar(String sliderName, String windowName, int sliderMin, int sliderMax, int defaultSlider, int *sliderVal, void(*f)(int, void *), void *r)
{
createTrackbar(sliderName, windowName, sliderVal, 1, f, r);
setTrackbarMin(sliderName, windowName, sliderMin);
setTrackbarMax(sliderName, windowName, sliderMax);
setTrackbarPos(sliderName, windowName, defaultSlider);
}
void UpdateThreshold(int , void * r)
{
Histo3DData *h = (Histo3DData *)r;
h->status=true;
h->threshold = h->seuil/1000000.0;
cout<<"部件 : "<<h->nbWidget<<","<< h->threshold<<"\n";
}
int main (int argc,char **argv)
{
CommandLineParser parser(argc, argv, keys);
if (parser.has("help"))
{
parser.printMessage();
return 0;
}
String nomFic = parser.get<String>(0);
Mat img;
if (nomFic.length() != 0)
{
img = imread(nomFic, IMREAD_COLOR);
if (img.empty())
{
cout << "图像不存在!";
return 0;
}
}
else
{
img = Mat(512,512,CV_8UC3);
parser.printMessage();
RNG r;
r.fill(img(Rect(0, 0, 256, 256)), RNG::NORMAL, Vec3b(60, 40, 50), Vec3b(10, 5, 20));
r.fill(img(Rect(256, 0, 256, 256)), RNG::NORMAL, Vec3b(160, 10, 50), Vec3b(20, 5, 10));
r.fill(img(Rect(0, 256, 256, 256)), RNG::NORMAL, Vec3b(90, 100, 50), Vec3b(10, 20, 20));
r.fill(img(Rect(256, 256, 256, 256)), RNG::NORMAL, Vec3b(100, 10, 150), Vec3b(10, 5, 40));
}
Histo3DData h;
h.status=true;
h.seuil=90;
h.threshold= h.seuil/1000000.0;
float hRange[] = { 0, 256 };
const float* etendu[] = { hRange, hRange,hRange };
int hBins = 32;
int histSize[] = { hBins, hBins , hBins };
int channel[] = { 2, 1,0 };
calcHist(&img, 1, channel, Mat(), h.histogram, 3, histSize, etendu, true, false);
normalize(h.histogram, h.histogram, 100.0/(img.total()), 0, NORM_MINMAX, -1, Mat());
minMaxIdx(h.histogram,NULL,&h.maxH,NULL,NULL);
namedWindow("图像");
imshow("图像",img);
AddSlidebar("阈值","图像",0,100,h.seuil,&h.seuil, UpdateThreshold,&h);
waitKey(30);
h.fen3D = makePtr<viz::Viz3d>("3D 直方图");
h.nbWidget=0;
h.fen3D->registerKeyboardCallback(KeyboardViz3d,&h);
DrawHistogram3D(h);
while (h.code!=27)
{
h.fen3D->spinOnce(1);
if (h.status)
DrawHistogram3D(h);
if (h.code!=27)
h.code= waitKey(30);
}
return 0;
}
#else
int main(int argc, char **argv)
{
cout << "你需要 VIZ 模块\n";
return 0;
}
#endif
如果数组没有元素,则返回 true。
int64_t int64
n 维密集数组类
定义 mat.hpp:830
用于表示由其x、y和z坐标指定的3D点的模板类。
定义 types.hpp:255
随机数生成器。
Definition core.hpp:2879
void fill(InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange=false)
用随机数填充数组。
2D 矩形的模板类。
定义 types.hpp:444
用于短数值向量的模板类,是 Matx 的一个特例。
定义 matx.hpp:369
此类表示 BGR 顺序的颜色。
定义 types.hpp:64
此类表示键盘事件。
cv::viz::KeyboardEvent::symbol
定义 types.hpp:303
cv::viz::KeyboardEvent::action
定义 types.hpp:302
Viz3d 类表示 3D 可视化窗口。此类是隐式共享的。
unsigned char code
定义 types.hpp:304
复合部件。
定义 widgets.hpp:514
此 3D 小部件定义一个立方体。
定义 widgets.hpp:373
void minMaxIdx(InputArray src, double *minVal, double *maxVal=0, int *minIdx=0, int *maxIdx=0, InputArray mask=noArray())
查找数组中的全局最小值和最大值。
void normalize(InputArray src, InputOutputArray dst, double alpha=1, double beta=0, int norm_type=NORM_L2, int dtype=-1, InputArray mask=noArray())
对数组的范数或值范围进行归一化。
std::string String
定义 cvstd.hpp:151
std::shared_ptr< _Tp > Ptr
Definition cvstd_wrapper.hpp:23
CV_8UC3
#define CV_8UC3
void imshow(const String &winname, InputArray mat)
在指定窗口中显示图像。
int waitKey(int delay=0)
等待按键按下。
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
创建窗口。
void setTrackbarPos(const String &trackbarname, const String &winname, int pos)
设置滑动条位置。
void setTrackbarMax(const String &trackbarname, const String &winname, int maxval)
设置滑动条最大位置。
void setTrackbarMin(const String &trackbarname, const String &winname, int minval)
设置滑动条最小位置。
int createTrackbar(const String &trackbarname, const String &winname, int *value, int count, TrackbarCallback onChange=0, void *userdata=0)
创建滑动条并将其附加到指定窗口。
CV_EXPORTS_W Mat imread(const String &filename, int flags=IMREAD_COLOR_BGR)
从文件加载图像。
void calcHist(const Mat *images, int nimages, const int *channels, InputArray mask, OutputArray hist, int dims, const int *histSize, const float **ranges, bool uniform=true, bool accumulate=false)
计算一组数组的直方图。
int main(int argc, char *argv[])
定义 highgui_qt.cpp:3
定义 core.hpp:107
STL 命名空间。

解释

这是程序的一般结构

  • 你可以在命令行中提供图像的完整路径

    CommandLineParser parser(argc, argv, keys);
    if (parser.has("help"))
    {
    parser.printMessage();
    return 0;
    }
    String nomFic = parser.get<String>(0);
    Mat img;
    if (nomFic.length() != 0)
    {
    img = imread(nomFic, IMREAD_COLOR);
    if (img.empty())
    {
    cout << "图像不存在!";
    return 0;
    }
    }

    或者不带路径,将生成一个合成图像,其像素值呈高斯分布,cv::RNG::fill 中心在第一象限为(60+/-10,40+/-5,50+/-20),在第二象限为(160+/-20,10+/-5,50+/-10),在第三象限为(90+/-10,100+/-20,50+/-20),在第四象限为(100+/-10,10+/-5,150+/-40)。

    else
    {
    img = Mat(512,512,CV_8UC3);
    parser.printMessage();
    RNG r;
    r.fill(img(Rect(0, 0, 256, 256)), RNG::NORMAL, Vec3b(60, 40, 50), Vec3b(10, 5, 20));
    r.fill(img(Rect(256, 0, 256, 256)), RNG::NORMAL, Vec3b(160, 10, 50), Vec3b(20, 5, 10));
    r.fill(img(Rect(0, 256, 256, 256)), RNG::NORMAL, Vec3b(90, 100, 50), Vec3b(10, 20, 20));
    r.fill(img(Rect(256, 256, 256, 256)), RNG::NORMAL, Vec3b(100, 10, 150), Vec3b(10, 5, 40));
    }

    图像三维直方图使用 OpenCV 的 cv::calcHist 和 cv::normalize 函数在0到100之间进行计算。

    Histo3DData h;
    h.status=true;
    h.seuil=90;
    h.threshold= h.seuil/1000000.0;
    float hRange[] = { 0, 256 };
    const float* etendu[] = { hRange, hRange,hRange };
    int hBins = 32;
    int histSize[] = { hBins, hBins , hBins };
    int channel[] = { 2, 1,0 };
    calcHist(&img, 1, channel, Mat(), h.histogram, 3, histSize, etendu, true, false);
    normalize(h.histogram, h.histogram, 100.0/(img.total()), 0, NORM_MINMAX, -1, Mat());
    minMaxIdx(h.histogram,NULL,&h.maxH,NULL,NULL);

    通道为2、1和0,用于将颜色与对象 cv::viz::WCoordinateSystem 中的 Viz 轴颜色同步。

    图像窗口中插入了一个滑块。初始滑块值为90,这意味着只有大于9/100000.0(对于512x512像素图像,这相当于23个像素)的直方图单元格才会被显示。

    namedWindow("图像");
    imshow("图像",img);
    AddSlidebar("阈值","图像",0,100,h.seuil,&h.seuil, UpdateThreshold,&h);
    waitKey(30);

    我们准备打开一个 Viz 窗口,并使用回调函数捕获 Viz 窗口中的键盘事件。使用 cv::viz::Viz3d::spinOnce 也能在 cv::imshow 窗口中捕获键盘事件。

    h.fen3D = makePtr<viz::Viz3d>("3D 直方图");
    h.nbWidget=0;
    h.fen3D->registerKeyboardCallback(KeyboardViz3d,&h);
    DrawHistogram3D(h);
    while (h.code!=27)
    {
    h.fen3D->spinOnce(1);
    if (h.status)
    DrawHistogram3D(h);
    if (h.code!=27)
    h.code= waitKey(30);
    }

    DrawHistogram3D 函数处理直方图 Mat 以在 Viz 窗口中显示它。三维 Mat 中的平面、行和列的数量可以使用此代码找到

    int planSize = (int)h.histogram.step1(0);
    int cols = (int)h.histogram.step1(1);
    int rows = (int)planSize / cols;
    int plans = (int)h.histogram.total() / planSize;
    h.fen3D->removeAllWidgets();
    h.nbWidget=0;
    if (h.nbWidget==0)
    h.fen3D->showWidget("Axis", viz::WCoordinateSystem(10));

    为了获取特定位置的直方图值,我们使用 cv::Mat::at(int i0,int i1, int i2) 方法,它有三个参数 k、i 和 j,其中 k 是平面数,i 是行数,j 是列数。

    for (int k = 0; k < plans; k++)
    {
    for (int i = 0; i < rows; i++)
    {
    for (int j = 0; j < cols; j++)
    {
    double x = h.histogram.at<float>(k, i, j);
    if (x >= h.threshold)
    {
    double r=std::max(x/h.maxH,0.1);
    viz::WCube s(Point3d(k - r / 2, i - r / 2, j - r / 2), Point3d(k + r / 2, i + r / 2, j + r / 2), false, viz::Color(j / double(plans) * 255, i / double(rows) * 255, k / double(cols) * 255));
    h.fen3D->showWidget(format("I3d%d", h.nbWidget++), s);
    }
    }
    }
    }
  • 回调函数的原理与鼠标回调函数相同。按下的键码在 cv::viz::KeyboardEvent 类的 code 字段中。
    void KeyboardViz3d(const viz::KeyboardEvent &w, void *t)
    {
    Histo3DData *x=(Histo3DData *)t;
    if (w.action)
    cout << "你按下了 "<< w.symbol<< " 在 viz 窗口 "<<x->fen3D->getWindowName()<<"\n";
    x->code= w.code;
    switch (w.code) {
    case '/'
    x->status=true;
    x->threshold *= 0.9;
    break;
    case '*'
    x->status = true;
    x->threshold *= 1.1;
    break;
    }
    if (x->status)
    {
    cout << x->threshold << "\n";
    DrawHistogram3D(*x);
    }
    }

结果

以下是程序在不带任何参数且阈值等于50时的结果。