#include"camera.h"
|
|
|
bool Camera::initConfig(float threshold, float cropRatio, float cellSize, float ratio,int size) {
|
CropRatio=cropRatio;
|
Threshold =threshold;
|
CellSize =cellSize;
|
Size=size;
|
threshold0=size*size*ratio;
|
return true;
|
}
|
|
std::vector<int> Camera::aHash(cv::Mat image) {
|
cv::Mat resized_image;
|
cv::resize(image,resized_image,cv::Size(Size,Size));
|
resized_image.convertTo(resized_image,CV_32FC3);
|
cv::Scalar meanValue = cv::mean(resized_image);
|
|
double avreage = meanValue[0];
|
|
std::vector<int> hash;
|
for (int i = 0; i < Size; i++) {
|
char* line = resized_image.ptr<char>(i);
|
for (int j = 0; j < Size; j++) {
|
|
if (line[j]>avreage) {
|
hash.push_back(1);
|
}
|
else {
|
hash.push_back(0);
|
}
|
}
|
}
|
|
|
return hash;
|
|
}
|
|
int Camera::Hamming_distance(std::vector<int> hash1, std::vector<int> hash2) {
|
int dist = 0;
|
for (int i = 0; i < hash1.size(); i++) {
|
if (hash1[i] != hash2[i]) {
|
dist++;
|
}
|
}
|
return dist;
|
}
|
|
int Camera::detect(cv::Mat& image,cv::Mat& standard)
|
{
|
try
|
{
|
int imageWidth = image.cols;
|
int imageHeight = image.rows;
|
|
int standardWidth = standard.cols;
|
int standardHeight = standard.rows;
|
|
int w1 = (1 - 2 * CropRatio) * imageWidth;
|
int h1 = (1 - 2 * CropRatio) * imageHeight;
|
|
int w2 = (1 - 2 * CropRatio) * standardWidth;
|
int h2 = (1 - 2 * CropRatio) * standardHeight;
|
|
cv::Mat im1, im2;
|
cv::Rect rect1((int)(CropRatio * imageWidth), (int)(CropRatio * imageHeight), w1, h1);
|
cv::Rect rect2((int)(CropRatio * standardWidth), (int)(CropRatio * standardHeight), w2, h2);
|
|
im1 = image(rect1);
|
im2 = standard(rect2);
|
|
//
|
cv::Mat gray1, gray2;
|
cv::cvtColor(im1, gray1, cv::COLOR_BGR2GRAY);
|
cv::cvtColor(im2, gray2, cv::COLOR_BGR2GRAY);
|
|
//计算格子大小
|
int step_w1 = w1 / CellSize;
|
int step_h1 = h1 / CellSize;
|
|
int step_w2 = w2 / CellSize;
|
int step_h2 = h2 / CellSize;
|
|
double n = 0;
|
for (int i = 0; i < CellSize; i++) {
|
for (int j = 0; j < CellSize; j++) {
|
cv::Mat roi1, roi2;
|
cv::Rect rect1(j * step_w1, i * step_h1, step_w1 - 1, step_h1 - 1);
|
cv::Rect rect2(j * step_w2, i * step_h2, step_w2 - 1, step_h2 - 1);
|
roi1 = gray1(rect1);
|
roi2 = gray2(rect2);
|
std::vector<int> hash1 = aHash(roi1);
|
std::vector<int> hash2 = aHash(roi2);
|
int dist = Hamming_distance(hash1, hash2);
|
//相同
|
if (dist < threshold0) {
|
continue;
|
}
|
|
n++;
|
}
|
}
|
|
//
|
if (n / (CellSize * CellSize) > Threshold) {
|
|
return 1;//异常
|
}
|
else {
|
return 0;//正常
|
}
|
}
|
catch (const std::exception& ex)
|
{
|
std::string errorMessage = "camera-";
|
errorMessage += ex.what();
|
throw std::runtime_error(errorMessage);
|
}
|
}
|