【Opencv测试用例(三)】


Chapter04

3、histograms.cpp

结果

在这里插入图片描述
在这里插入图片描述

测试代码


#include <iostream>
#include<opencv2/opencv.hpp>
using namespace std;
#include "histogram.h"

static int test()
{
	// Read input image
	std::string path_group = "F:/images/group.jpg";
	cv::Mat image = cv::imread(path_group, 0);
	if (!image.data)
		return 0;

	// save grayscale image
	std::string path_groupBW1 = "F:/images/groupBW1.jpg";
	cv::imwrite(path_groupBW1, image);

	// Display the image
	cv::namedWindow("Image");
	cv::imshow("Image", image);

	// The histogram object
	Histogram1D h;

	// Compute the histogram
	cv::Mat histo = h.getHistogram(image);

	// Loop over each bin
	for (int i = 0; i < 256; i++)
		cout << "Value " << i << " = " << histo.at<float>(i) << endl;

	// Display a histogram as an image
	cv::namedWindow("Histogram");
	cv::imshow("Histogram", h.getHistogramImage(image));

	// re-display the histagram with chosen threshold indicated
	cv::Mat hi = h.getHistogramImage(image);
	cv::line(hi, cv::Point(70, 0), cv::Point(70, 255), cv::Scalar(128));
	cv::namedWindow("Histogram with threshold value");
	cv::imshow("Histogram with threshold value", hi);

	// creating a binary image by thresholding at the valley
	cv::Mat thresholded; // output binary image
	cv::threshold(image, thresholded,
		70,    // threshold value
		255,   // value assigned to pixels over threshold value
		cv::THRESH_BINARY); // thresholding type

// Display the thresholded image
	cv::namedWindow("Binary Image");
	cv::imshow("Binary Image", thresholded);
	thresholded = 255 - thresholded;
	cv::imwrite("binary.bmp", thresholded);

	// Equalize the image
	cv::Mat eq = h.equalize(image);

	// Show the result
	cv::namedWindow("Equalized Image");
	cv::imshow("Equalized Image", eq);

	// Show the new histogram
	cv::namedWindow("Equalized H");
	cv::imshow("Equalized H", h.getHistogramImage(eq));

	// Stretch the image, setting the 1% of pixels at black and 1% at white
	cv::Mat str = h.stretch(image, 0.01f);

	// Show the result
	cv::namedWindow("Stretched Image");
	cv::imshow("Stretched Image", str);

	// Show the new histogram
	cv::namedWindow("Stretched H");
	cv::imshow("Stretched H", h.getHistogramImage(str));

	// Create an image inversion table
	cv::Mat lut(1, 256, CV_8U); // 1x256 matrix

	// Or:
	// int dim(256);
	// cv::Mat lut(1,  // 1 dimension
	// 	&dim,          // 256 entries
	//	CV_8U);        // uchar

	for (int i = 0; i < 256; i++) {

		// 0 becomes 255, 1 becomes 254, etc.
		lut.at<uchar>(i) = 255 - i;
	}

	// Apply lookup and display negative image
	cv::namedWindow("Negative image");
	cv::imshow("Negative image", h.applyLookUp(image, lut));

	cv::waitKey();
	return 0;
}

int main()
{
	test();
	system("pause");
	return 0;
}

提示:#include "histogram.h"见opencv测试用例二中

4、integral.cpp

结果

在这里插入图片描述

测试代码


#include <iostream>
#include<opencv2/opencv.hpp>

#include "integral.h"

static int test()
{
	std::string path_book = "F:/images/book.jpg";
	cv::Mat image = cv::imread(path_book, 0);
	if (!image.data)
		return 0;
	// rotate the image for easier display
	cv::transpose(image, image);
	cv::flip(image, image, 0);

	// display original image
	cv::namedWindow("Original Image");
	cv::imshow("Original Image", image);

	// using a fixed threshold 
	cv::Mat binaryFixed;
	cv::Mat binaryAdaptive;
	cv::threshold(image, binaryFixed, 70, 255, cv::THRESH_BINARY);

	// using as adaptive threshold
	int blockSize = 21; // size of the neighborhood
	int threshold = 10;  // pixel will be compared to (mean-threshold)

	int64 time;
	time = cv::getTickCount();
	cv::adaptiveThreshold(image,           // input image
		binaryAdaptive,  // output binary image
		255,             // max value for output
		cv::ADAPTIVE_THRESH_MEAN_C, // adaptive method
		cv::THRESH_BINARY, // threshold type
		blockSize,       // size of the block
		threshold);      // threshold used
	time = cv::getTickCount() - time;
	std::cout << "time (adaptiveThreshold)= " << time << std::endl;

	// compute integral image
	IntegralImage<int, 1> integral(image);

	// test integral result
	std::cout << "sum=" << integral(18, 45, 30, 50) << std::endl;
	cv::Mat test(image, cv::Rect(18, 45, 30, 50));
	cv::Scalar t = cv::sum(test);
	std::cout << "sum test=" << t[0] << std::endl;

	cv::namedWindow("Fixed Threshold");
	cv::imshow("Fixed Threshold", binaryFixed);

	cv::namedWindow("Adaptive Threshold");
	cv::imshow("Adaptive Threshold", binaryAdaptive);

	cv::Mat binary = image.clone();

	time = cv::getTickCount();
	int nl = binary.rows; // number of lines
	int nc = binary.cols; // total number of elements per line

	// compute integral image
	cv::Mat iimage;
	cv::integral(image, iimage, CV_32S);

	// for each row
	int halfSize = blockSize / 2;
	for (int j = halfSize; j < nl - halfSize - 1; j++) {

		// get the address of row j
		uchar* data = binary.ptr<uchar>(j);
		int* idata1 = iimage.ptr<int>(j - halfSize);
		int* idata2 = iimage.ptr<int>(j + halfSize + 1);

		// for pixel of a line
		for (int i = halfSize; i < nc - halfSize - 1; i++) {

			// compute sum
			int sum = (idata2[i + halfSize + 1] - idata2[i - halfSize] -
				idata1[i + halfSize + 1] + idata1[i - halfSize]) / (blockSize*blockSize);

			// apply adaptive threshold
			if (data[i] < (sum - threshold))
				data[i] = 0;
			else
				data[i] = 255;
		}
	}

	// add white border
	for (int j = 0; j < halfSize; j++) {
		uchar* data = binary.ptr<uchar>(j);

		for (int i = 0; i < binary.cols; i++) {
			data[i] = 255;
		}
	}
	for (int j = binary.rows - halfSize - 1; j < binary.rows; j++) {
		uchar* data = binary.ptr<uchar>(j);

		for (int i = 0; i < binary.cols; i++) {
			data[i] = 255;
		}
	}
	for (int j = halfSize; j < nl - halfSize - 1; j++) {
		uchar* data = binary.ptr<uchar>(j);

		for (int i = 0; i < halfSize; i++) {
			data[i] = 255;
		}
		for (int i = binary.cols - halfSize - 1; i < binary.cols; i++) {
			data[i] = 255;
		}
	}

	time = cv::getTickCount() - time;
	std::cout << "time integral= " << time << std::endl;

	cv::namedWindow("Adaptive Threshold (integral)");
	cv::imshow("Adaptive Threshold (integral)", binary);

	// adaptive threshold using image operators
	time = cv::getTickCount();
	cv::Mat filtered;
	cv::Mat binaryFiltered;
	// box filter compute avg of pixels over a rectangular region
	cv::boxFilter(image, filtered, CV_8U, cv::Size(blockSize, blockSize));
	// check if pixel greater than (mean + threshold)
	binaryFiltered = image >= (filtered - threshold);
	time = cv::getTickCount() - time;

	std::cout << "time filtered= " << time << std::endl;

	cv::namedWindow("Adaptive Threshold (filtered)");
	cv::imshow("Adaptive Threshold (filtered)", binaryFiltered);

	cv::waitKey();
}

int main()
{
	test();
	system("pause");
	return 0;
}

integral.h头文件



#if !defined IINTEGRAL
#define IINTEGRAL

#include<opencv2/opencv.hpp>
#include <vector>

template <typename T, int N>
class IntegralImage {

	cv::Mat integralImage;

public:

	IntegralImage(cv::Mat image) {

		// (costly) computation of the integral image
		cv::integral(image, integralImage, cv::DataType<T>::type);
	}

	// compute sum over sub-regions of any size from 4 pixel access
	cv::Vec<T, N> operator()(int xo, int yo, int width, int height) {

		// window at (xo,yo) of size width by height
		return (integralImage.at<cv::Vec<T, N> >(yo + height, xo + width)
			- integralImage.at<cv::Vec<T, N> >(yo + height, xo)
			- integralImage.at<cv::Vec<T, N> >(yo, xo + width)
			+ integralImage.at<cv::Vec<T, N> >(yo, xo));
	}

	// compute sum over sub-regions of any size from 4 pixel access
	cv::Vec<T, N> operator()(int x, int y, int radius) {

		// square window centered at (x,y) of size 2*radius+1
		return (integralImage.at<cv::Vec<T, N> >(y + radius + 1, x + radius + 1)
			- integralImage.at<cv::Vec<T, N> >(y + radius + 1, x - radius)
			- integralImage.at<cv::Vec<T, N> >(y - radius, x + radius + 1)
			+ integralImage.at<cv::Vec<T, N> >(y - radius, x - radius));
	}
};

// convert to a multi-channel image made of binary planes
// nPlanes must be a power of 2
static void convertToBinaryPlanes(const cv::Mat& input, cv::Mat& output, int nPlanes) {

	// number of bits to mask out
	int n = 8 - static_cast<int>(log(static_cast<double>(nPlanes)) / log(2.0));
	// mask used to eliminate least significant bits
	uchar mask = 0xFF << n; // e.g. for div=16, mask= 0xF0

	// create a vector of 16 binary images
	std::vector<cv::Mat> planes;
	// reduce to nBins bins by eliminating least significant bits
	cv::Mat reduced = input & mask;

	// compute each binary image plane
	for (int i = 0; i < nPlanes; i++) {

		// 1 for each pixel equals to i<<shift
		planes.push_back((reduced == (i << n)) & 0x1);
	}

	// create multi-channel image
	cv::merge(planes, output);
}

#endif

5、retrieve.cpp

结果

在这里插入图片描述
waves vs dog: 26535
waves vs marais: 12149
waves vs bear: 18353
waves vs beach: 33032
waves vs polar: 20768
waves vs moose: 15225
waves vs lake: 15486
waves vs fundy: 14309

测试代码

#include <iostream>
using namespace std;
#include<opencv2/opencv.hpp>
#include "imageComparator.h"

static int test()
{
	// Read reference image
	std::string path_waves = "F:/images/waves.jpg";
	cv::Mat image = cv::imread(path_waves);
	if (!image.data)
		return 0;

	// Display image
	cv::namedWindow("Query Image");
	cv::imshow("Query Image", image);

	ImageComparator c;
	c.setReferenceImage(image);

	// Read an image and compare it with reference
	std::string path_dog = "F:/images/dog.jpg";
	cv::Mat input = cv::imread(path_dog);
	cv::imshow("path_dog", input);
	cout << "waves vs dog: " << c.compare(input) << endl;

	// Read an image and compare it with reference
	std::string path_marais = "F:/images/marais.jpg";
	input = cv::imread(path_marais);
	cv::imshow("path_marais", input);
	cout << "waves vs marais: " << c.compare(input) << endl;

	// Read an image and compare it with reference
	std::string path_bear = "F:/images/bear.jpg";
	input = cv::imread(path_bear);
	cv::imshow("path_bear", input);
	cout << "waves vs bear: " << c.compare(input) << endl;

	// Read an image and compare it with reference
	std::string path_beach = "F:/images/beach.jpg";
	input = cv::imread(path_beach);
	cv::imshow("path_beach", input);
	cout << "waves vs beach: " << c.compare(input) << endl;

	// Read an image and compare it with reference
	std::string path_polar = "F:/images/polar.jpg";
	input = cv::imread(path_polar);
	cv::imshow("path_polar", input);
	cout << "waves vs polar: " << c.compare(input) << endl;

	// Read an image and compare it with reference
	std::string path_moose = "F:/images/moose.jpg";
	input = cv::imread(path_moose);
	cv::imshow("path_moose", input);
	cout << "waves vs moose: " << c.compare(input) << endl;

	// Read an image and compare it with reference
	std::string path_lake = "F:/images/lake.jpg";
	input = cv::imread(path_lake);
	cv::imshow("path_lake", input);
	cout << "waves vs lake: " << c.compare(input) << endl;

	// Read an image and compare it with reference
	std::string path_fundy = "F:/images/fundy.jpg";
	input = cv::imread(path_fundy);
	cv::imshow("path_fundy", input);
	cout << "waves vs fundy: " << c.compare(input) << endl;
	cv::waitKey();
	return 0;
}

int main()
{
	test();
	system("pause");
	return 0;
}

6、tracking.cpp

结果

在这里插入图片描述

测试代码

#include <iostream>
#include<opencv2/opencv.hpp>
#include <vector>
#include "histogram.h"
#include "integral.h"

static int test()
{
	// Open image
	std::string path_bike55 = "F:/images/bike55.bmp";
	cv::Mat image = cv::imread(path_bike55, 0);
	// define image roi
	int xo = 97, yo = 112;
	int width = 25, height = 30;
	cv::Mat roi(image, cv::Rect(xo, yo, width, height));

	// compute sum
	// returns a Scalar to work with multi-channel images
	cv::Scalar sum = cv::sum(roi);
	std::cout << sum[0] << std::endl;

	// compute integral image
	cv::Mat integralImage;
	cv::integral(image, integralImage, CV_32S);
	// get sum over an area using three additions/subtractions
	int sumInt = integralImage.at<int>(yo + height, xo + width)
		- integralImage.at<int>(yo + height, xo)
		- integralImage.at<int>(yo, xo + width)
		+ integralImage.at<int>(yo, xo);
	std::cout << sumInt << std::endl;

	// histogram of 16 bins
	Histogram1D h;
	h.setNBins(16);
	// compute histogram over image roi 
	cv::Mat refHistogram = h.getHistogram(roi);

	cv::namedWindow("Reference Histogram");
	cv::imshow("Reference Histogram", h.getHistogramImage(roi, 16));
	std::cout << refHistogram << std::endl;

	// first create 16-plane binary image
	cv::Mat planes;
	convertToBinaryPlanes(image, planes, 16);
	// then compute integral image
	IntegralImage<float, 16> intHisto(planes);


	// for testing compute a histogram of 16 bins with integral image
	cv::Vec<float, 16> histogram = intHisto(xo, yo, width, height);
	std::cout << histogram << std::endl;

	cv::namedWindow("Reference Histogram (2)");
	cv::Mat im = h.getImageOfHistogram(cv::Mat(histogram), 16);
	cv::imshow("Reference Histogram (2)", im);

	// search in second image
	std::string path_bike65 = "F:/images/bike65.bmp";
	cv::Mat secondImage = cv::imread(path_bike65, 0);
	if (!secondImage.data)
		return 0;

	// first create 16-plane binary image
	convertToBinaryPlanes(secondImage, planes, 16);
	// then compute integral image
	IntegralImage<float, 16> intHistogram(planes);

	// compute histogram of 16 bins with integral image (testing)
	histogram = intHistogram(135, 114, width, height);
	std::cout << histogram << std::endl;

	cv::namedWindow("Current Histogram");
	cv::Mat im2 = h.getImageOfHistogram(cv::Mat(histogram), 16);
	cv::imshow("Current Histogram", im2);

	std::cout << "Distance= " << cv::compareHist(refHistogram, histogram, cv::HISTCMP_INTERSECT) << std::endl;

	double maxSimilarity = 0.0;
	int xbest, ybest;
	// loop over a horizontal strip around girl location in initial image
	for (int y = 110; y < 120; y++) {
		for (int x = 0; x < secondImage.cols - width; x++) {


			// compute histogram of 16 bins using integral image
			histogram = intHistogram(x, y, width, height);
			// compute distance with reference histogram
			double distance = cv::compareHist(refHistogram, histogram, cv::HISTCMP_INTERSECT);
			// find position of most similar histogram
			if (distance > maxSimilarity) {

				xbest = x;
				ybest = y;
				maxSimilarity = distance;
			}

			std::cout << "Distance(" << x << "," << y << ")=" << distance << std::endl;
		}
	}

	std::cout << "Best solution= (" << xbest << "," << ybest << ")=" << maxSimilarity << std::endl;

	// draw a rectangle around target object
	cv::rectangle(image, cv::Rect(xo, yo, width, height), 0);
	cv::namedWindow("Initial Image");
	cv::imshow("Initial Image", image);

	cv::namedWindow("New Image");
	cv::imshow("New Image", secondImage);
	// draw rectangle at best location
	cv::rectangle(secondImage, cv::Rect(xbest, ybest, width, height), 0);
	// draw rectangle around search area
	cv::rectangle(secondImage, cv::Rect(0, 110, secondImage.cols, height + 10), 255);
	cv::namedWindow("Object location");
	cv::imshow("Object location", secondImage);
	cv::waitKey();
}

int main()
{
	test();
	system("pause");
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值