Assertion failed in my OpenCV program - opencv

My program is the another edition of the OpenCV Harris and Shi-Tomasi corner detection.
I just added a little code into it to change the image corner detection into video corner detection. However, it came out one faulty which I can't deal with. (cv::Exception).
This is my program:
#include "stdafx.h"
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
double Harris_minVal;
double Harris_maxVal;
double ShiTomasi_minVal;
double ShiTomasi_maxVal;
int Harris_qualityLevel = 50;
int ShiTomasi_qualityLevel = 50;
int max_qualityLevel = 100;
RNG rng(12345);
const char* Harris_window = "Harris Corner Detection";
const char* ShiTomasi_window = "ShiTomasi Corner Detection";
Mat frame, frame_gray, Harris_dst, Harris_copy, ShiTomasi_dst, ShiTomasi_copy,Mc;
void HarrisFunction(int, void*);
void ShiTomasiFunction(int, void*);
int main()
{
VideoCapture capture(0);
while (1) {
capture >> frame;
cvtColor(frame, frame_gray, COLOR_BGR2GRAY);
int blockSize = 3;
int kSize = 3;
Harris_dst = Mat::zeros(frame_gray.size(), CV_32FC(6));
Mc = Mat::zeros(frame_gray.size(), CV_32FC1);
cornerEigenValsAndVecs(frame_gray, Harris_dst, blockSize, kSize, BORDER_DEFAULT);
for (int j = 0; j < frame_gray.rows; j++) {
for (int i = 0; i < frame_gray.cols; i++) {
float lambda_1 = Harris_dst.at<Vec6f>(j, i)[0];
float lambda_2 = Harris_dst.at<Vec6f>(j, i)[1];
Mc.at<float>(j, i) = lambda_1*lambda_2 - 0.04f*pow((lambda_1 + lambda_2), 2);
}
}
minMaxLoc(Mc, &Harris_minVal, &Harris_maxVal, 0, 0, Mat());
namedWindow(Harris_window, WINDOW_AUTOSIZE);
createTrackbar("质量:", Harris_window, &Harris_qualityLevel, max_qualityLevel, HarrisFunction);
HarrisFunction(0, 0);
ShiTomasi_dst = Mat::zeros(frame_gray.size(), CV_32FC1);
cornerEigenValsAndVecs(frame_gray, ShiTomasi_dst, blockSize, kSize, BORDER_DEFAULT);
minMaxLoc(ShiTomasi_dst, &ShiTomasi_minVal, &ShiTomasi_maxVal, 0, 0, Mat());
namedWindow(ShiTomasi_window, WINDOW_AUTOSIZE);
createTrackbar(" 质量:", ShiTomasi_window, &ShiTomasi_qualityLevel, max_qualityLevel, ShiTomasiFunction);
ShiTomasiFunction(0, 0);
}
return 0;
}
void HarrisFunction(int, void*) {
Harris_copy = frame.clone();
if (Harris_qualityLevel < 1) {
Harris_qualityLevel = 1;
}
for (int j = 0; j <= frame_gray.rows; j++) {
for (int i = 0; i <= frame_gray.cols; i++) {
if (Mc.at<float>(j, i) > Harris_minVal + (Harris_maxVal - Harris_minVal)*(Harris_qualityLevel / max_qualityLevel))
{
circle(Harris_copy, Point(i, j), 4, Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)),1,8,0);
}
}
}
imshow(Harris_window, Harris_copy);
waitKey(30);
}
void ShiTomasiFunction(int, void*) {
ShiTomasi_copy = frame.clone();
if (ShiTomasi_qualityLevel < 1) {
ShiTomasi_qualityLevel = 1;
}
for (int j = 0; j <= frame_gray.rows; j++) {
for (int i = 0; i <= frame_gray.cols; i++) {
if (ShiTomasi_dst.at<float>(j, i) > ShiTomasi_minVal + (ShiTomasi_maxVal - ShiTomasi_minVal)*(ShiTomasi_qualityLevel / max_qualityLevel))
{
circle(ShiTomasi_copy, Point(i, j), 4, Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)), 1, 8, 0);
}
}
}
imshow(ShiTomasi_window, ShiTomasi_copy);
waitKey(30);
}
After my debug, the Problem is before imshow(Harris_window,Harris_copy):
OpenCV Error: Assertion failed (dims <= 2 && data && (unsigned)i0<(unsigned)size.p[0] && (unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels()) && ((((sizeof(size_t)<<28)|0x8442211) >> ((DataType<_Tp>::depth) & ((1<< 3) - 1))*4) & 15) == elemSize1()) in cv::Mat::at,filed:\opencv\build\include\opencv2\core\mat.inl.hpp, line 894
The upper part is what the panel window writes.

Related

Blurring creates stripes on the output image

I wrote this piece of code to make a median Blur in CUDA but I am running into an issue, where the channel of image is blurred but it creates stripes which look unusual for blurring.
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
using namespace std;
using namespace cv;
#define BLOCK_SIZE 16
#define TILE_SIZE 14
#define FILTER_WIDTH 3
#define FILTER_HEIGHT 3
__device__ void sort(unsigned char* filterVector)
{
for (int i = 0; i < FILTER_WIDTH*FILTER_HEIGHT; i++) {
for (int j = i + 1; j < FILTER_WIDTH*FILTER_HEIGHT; j++) {
if (filterVector[i] > filterVector[j]) {
unsigned char tmp = filterVector[i];
filterVector[i] = filterVector[j];
filterVector[j] = tmp;
}
}
}
}
__global__ void medianFilter(unsigned char *srcImage, unsigned char *dstImage, unsigned int width, unsigned int height)
{
int x_o = TILE_SIZE * blockIdx.x + threadIdx.x;
int y_o = TILE_SIZE * blockIdx.y + threadIdx.y;
int x_i = x_o - (FILTER_HEIGHT / 2);
int y_i = y_o - (FILTER_WIDTH / 2);
__shared__ unsigned char sBuffer[BLOCK_SIZE][BLOCK_SIZE];
if ((x_i >= 0) && (x_i < width) && (y_i >= 0) && (y_i < height)) {
sBuffer[threadIdx.y][threadIdx.x] = srcImage[y_i * width + x_i];
} else {
sBuffer[threadIdx.y][threadIdx.x] = 0;
}
__syncthreads();
unsigned char filterVector[FILTER_WIDTH*FILTER_HEIGHT];
// int size_vec = sizeof(filterVector) / sizeof(filterVector[0]);
// printf("%d \n", size_vec);
if (threadIdx.x < TILE_SIZE && threadIdx.y < TILE_SIZE) {
for (int r = 0; r < FILTER_HEIGHT; r++) {
for (int c = 0; c < FILTER_HEIGHT; c++) {
filterVector[r*FILTER_HEIGHT+c] = sBuffer[threadIdx.y + r][threadIdx.x + c];
}
}
}
sort(filterVector);
if (x_o < width && y_o < height) {
dstImage[y_o * width + x_o] = filterVector[4]; // (FILTER_WIDTH*FILTER_HEIGHT)/2
}
}
int main(int argc, char **argv)
{
std::string image_path = "./test.jpg";
cv::Mat img = imread(image_path, IMREAD_COLOR);
std::string output_file = "test_gpu.jpg";
if(img.empty())
{
std::cout << "Couldn't read img:" << image_path << std::endl;
}
Mat bgr[3];
split(img, bgr);
cv::Mat dstImg (bgr[1].size(), bgr[1].type());
const int inputSize = img.cols * img.rows;
const int outputSize = dstImg.cols * dstImg.rows;
unsigned char *d_input, *d_output;
cudaMalloc<unsigned char>(&d_input, inputSize);
cudaMalloc<unsigned char>(&d_output, outputSize);
cudaMemcpy(d_input, bgr[1].ptr(), inputSize, cudaMemcpyHostToDevice);
const dim3 block(BLOCK_SIZE, BLOCK_SIZE);
const dim3 grid((dstImg.cols + TILE_SIZE - 1)/TILE_SIZE, (dstImg.rows + TILE_SIZE - 1)/TILE_SIZE);
medianFilter<<<grid,block>>>(d_input, d_output, dstImg.cols, dstImg.rows);
cudaMemcpy(dstImg.ptr(), d_output, outputSize, cudaMemcpyDeviceToHost);
cudaFree(d_input);
cudaFree(d_output);
imwrite(output_file, dstImg);
}
This is my original image:
and here is one blurred channel:
For some reason I get those stripes on the output image, which is just one of the channels for now. Any idea why this is happening?
Your intention is that even though you are launching a block of dimension (BLOCK_SIZE, BLOCK_SIZE), you only intend (TILE_SIZE, TILE_SIZE) threads in that block to actually compute the values for output pixels.
However you are not properly accounting for that here:
if (x_o < width && y_o < height) {
that should be, instead:
if (x_o < width && y_o < height && threadIdx.x < TILE_SIZE && threadIdx.y < TILE_SIZE) {
(In fact, everything after the __syncthreads() in your kernel can be conditioned to only execute if threadIdx.x < TILE_SIZE && threadIdx.y < TILE_SIZE if you wish.)

Add snowfall effect to image/video using OpenCV [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Has anyone thought of creating snowfall effect on a video using OpenCV? If so, do you have any idea regarding the same?
Just as a sketch to give an idea :)
#include <windows.h>
#include <iostream>
#include <vector>
#include <stdio.h>
#include "fstream"
#include "iostream"
#include <algorithm>
#include <iterator>
#include <random>
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
//-----------------------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------------------
std::default_random_engine generator(time(NULL));
std::uniform_int_distribution<int> distribution;
std::uniform_int_distribution<int> distribution_bin;
void getGradient(Mat& src, Mat& mag, Mat& ang)
{
Mat src_g;
cvtColor(src, src_g, COLOR_BGR2GRAY);
src_g.convertTo(src_g, CV_32FC1,1.0/255.0);
GaussianBlur(src_g, src_g, Size(3, 3), 2);
Mat gx, gy;
Sobel(src_g, gx, -1, 1, 0);
Sobel(src_g, gy, -1, 0, 1);
magnitude(gx, gy, mag);
phase(gx, gy, ang, true);
}
//-----------------------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------------------
class snow
{
public:
float threshold;
float x;
float y;
float t;
float phase;
bool dead;
snow()
{
threshold = 0.5;
x = distribution(generator);
phase = distribution(generator);
y = 0;
dead = false;
}
void step(Mat& canvas, Mat& res_dead, Mat& mag, Mat& ang)
{
if(x<1)
{
x = 1;
}
if (x>canvas.cols-2)
{
x = canvas.cols-2;
}
float g = mag.at<float>(y+1, x);
float a = ang.at<float>(y+1, x);
float rdL = res_dead.at<Vec3b>(y + 1, x-1)[0];
float rdM = res_dead.at<Vec3b>(y + 1, x)[0];
float rdR = res_dead.at<Vec3b>(y + 1, x+1)[0];
if (rdL >0 && rdM > 0 && rdR == 0)
{
g = 10;
a = 20;
}
if (rdL == 0 && rdM > 0 && rdR > 0)
{
g = 10;
a = 140;
}
if (rdL > 0 && rdM > 0 && rdR > 0)
{
dead = true;
return;
}
if (rdL == 0 && rdM > 0 && rdR == 0)
{
int des= distribution_bin(generator);
if (des == 0)
{
a = 20;
}
else
{
a = 140;
}
}
if (g < threshold && rdM==0)
{
++y;
x += 1 * sin(t/10+phase);
}
++t;
if (g > threshold)
{
if (a < 45 && a > 10)
{
++y;
++x;
}else if (a > 135 && a < 170)
{
++y;
--x;
}
else
{
++y;
dead = true;
return;
}
}
if (x > mag.cols - 1)
{
// ++y;
x = mag.cols - 2;
dead = true;
return;
}
if (x < 0)
{
x = 1;
dead = true;
return;
}
if (y < 0)
{
y = 0;
dead = true;
return;
}
if (y >= mag.rows - 1)
{
y = mag.rows - 1;
dead = true;
return;
}
}
};
//-----------------------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------------------
int main(int argc, unsigned int** argv)
{
Mat src=imread("F:/ImagesForTest/lena.jpg",1);
Mat res = Mat::zeros(src.size(), src.type());
Mat res_dead = Mat::zeros(src.size(), src.type());
distribution = std::uniform_int_distribution<int>(0,src.cols-1);
distribution_bin = std::uniform_int_distribution<int>(0, 1);
Mat mag, ang;
Mat mag_s= Mat::zeros(src.size(), CV_32FC1);
Mat ang_s = Mat::zeros(src.size(), CV_32FC1);
Mat mag_sum, ang_sum;
getGradient(src, mag, ang);
vector<snow> s(100);
int key = 0;
while(key!=27)
{
mag_sum = mag + mag_s;
ang_sum = ang + ang_s;
for (int k = 0; k < 20; ++k)
{
snow sn;
s.push_back(sn);
}
for (int j = 0; j < s.size(); ++j)
{
s[j].step(res, res_dead, mag_sum, ang_sum);
if (s[j].y < 0)
{
s[j].y = 0;
}
res.at<Vec3b>(s[j].y, s[j].x) = Vec3b(255, 255, 255);
if (s[j].dead)
{
res_dead.at<Vec3b>(s[j].y, s[j].x) = Vec3b(255, 255, 255);
s.erase(s.begin() + j);
}
}
res += res_dead;
imshow("res", res+src);
key=waitKey(10);
res = 0;
}
imshow("src", src);
key=waitKey(0);
}

error in runing source face detection in opencv 2.4.9 and vs 2012

i use pre-build opencv 2.4.9 i test the image show in opencv 2.4.9 it works,but for this source its have error?! if this errors is that i use pre-build opencv?what to do what not to do
i copy the xml file in current folder and my hardware corei5,Radeon ATI graphic
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <opencv/ml.h>
void doMosaic(IplImage* in, int x, int y,
int width, int height, int size);
int main (int argc, char **argv)
{
int i, c;
IplImage *src_img = 0, *src_gray = 0;
const char *cascade_name = "haarcascade_frontalface_alt.xml";
CvHaarClassifierCascade *cascade = 0;
CvMemStorage *storage = 0;
CvSeq *faces;
cascade = (CvHaarClassifierCascade *) cvLoad (cascade_name, 0, 0, 0);
cvNamedWindow ("Capture", CV_WINDOW_AUTOSIZE);
CvCapture *capture = cvCreateCameraCapture(0);
assert(capture != NULL);
while (1) {
src_img = cvQueryFrame (capture);
src_gray = cvCreateImage (cvGetSize(src_img), IPL_DEPTH_8U, 1);
storage = cvCreateMemStorage (0);
cvClearMemStorage (storage);
cvCvtColor (src_img, src_gray, CV_BGR2GRAY);
cvEqualizeHist (src_gray, src_gray);
faces = cvHaarDetectObjects (src_gray, cascade, storage,
1.11, 4, 0, cvSize (40, 40));
for (i = 0; i < (faces ? faces->total : 0); i++) {
CvRect *r = (CvRect *) cvGetSeqElem (faces, i);
doMosaic(src_img, r->x, r->y, r->width, r->height, 20);
}
cvShowImage("Capture", src_img);
cvReleaseImage(&src_gray);
c = cvWaitKey (2);
if (c == '\x1b')
break;
}
cvReleaseCapture (&capture);
cvDestroyWindow ("Capture");
return 0;
}
void doMosaic(IplImage* in, int x0, int y0,
int width, int height, int size)
{
int b, g, r, col, row;
int xMin = size*(int)floor((double)x0/size);
int yMin = size*(int)floor((double)y0/size);
int xMax = size*(int)ceil((double)(x0+width)/size);
int yMax = size*(int)ceil((double)(y0+height)/size);
for(int y=yMin; y<yMax; y+=size){
for(int x=xMin; x<xMax; x+=size){
b = g = r = 0;
for(int i=0; i<size; i++){
if( y+i > in->height ){
break;
}
row = i;
for(int j=0; j<size; j++){
if( x+j > in->width ){
break;
}
b += (unsigned char)in->imageData[in->widthStep*(y+i)+(x+j)*3];
g += (unsigned char)in->imageData[in->widthStep*(y+i)+(x+j)*3+1];
r += (unsigned char)in->imageData[in->widthStep*(y+i)+(x+j)*3+2];
col = j;
}
}
row++;
col++;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
in->imageData[in->widthStep*(y+i)+(x+j)*3] = cvRound((double)b/(row*col));
in->imageData[in->widthStep*(y+i)+(x+j)*3+1] = cvRound((double)g/(row*col));
in->imageData[in->widthStep*(y+i)+(x+j)*3+2] = cvRound((double)r/(row*col));
}
}
}
}
}
the error is a break in microsoft ,please help me.thanks very much
First-chance exception at 0x75C4B727 in opencv.exe: Microsoft C++ exception: cv::Exception at memory location 0x003CF678.
If there is a handler for this exception, the program may be safely continued.
finally i succeed,i first for PDB errors tools>option>debugging>outputwindow>moduleloadmessage >off and then i tools>option>debugging>symbols>microsoft symbols server not checked and then i chnge capture.open( -1 ); to capture.open( 0 ); now by seting in opencv itworks,thanks very much

Cannot add 4 numbers to mat opencv

I created a mat object in opencv , dimension Nx4 , in which I want to put N coordinates.
[Px Py 1 0]
[Py Px 0 1]
For this I wrote the following code :
vector<Point2f> features1 , features2;
Mat features_1;
for(int i = 0 , j = 0; i < feature1.size() ; ++i , j+=2)
{
features_1.at<Vec3d>(j) = {feature1[i].x , feature1[i].y , 1 , 0};
features_1.at<Vec3d>(j) = {feature1[i].y , -feature1[i].x , 0 , 1};
}
But at the first line of the loop I get the following error :
cv::Matx<_Tp, m, n>::Matx(_Tp, _Tp, _Tp, _Tp) [with _Tp = double; int m = 3; int n = 1]: Assertion channels >= 4' failed.
How can I solve this?
it's probably easier to push_back() single elements to a Mat, and later do a reshape().
this will make a 2*N x 4 Mat:
vector<Point2f> features1 , features2;
Mat features_1;
for(size_t i=0; i<feature1.size() ; ++i)
{
features_1.push_pack(feature1[i].x);
features_1.push_pack(feature1[i].y);
features_1.push_pack(1);
features_1.push_pack(0);
features_1.push_pack(feature2[i].y);
features_1.push_pack(feature2[i].x);
features_1.push_pack(0);
features_1.push_pack(1);
}
features_1 = features_1.reshape(1,4); // or reshape(1,features1.size()*2); //for 4xN*2
Where you wrote <Vec3d>, did you mean <Vec4d>?
Your code is not close to correct, but here is a minimal example of how your desired result can be achieved (if you don't have C++11, just use an old style iterator in the loop)
#include <iostream>
#include <vector>
using namespace std;
#include <opencv2/core/core.hpp>
using namespace cv;
int main()
{
vector<Point2f> feature1;
feature1.push_back(Point2f(1.0f, 2.0f));
feature1.push_back(Point2f(3.0f, 4.0f));
Mat features_1;
for(auto p : feature1)
{
features_1.push_back(Vec4d(p.x, p.y , 1 , 0));
features_1.push_back(Vec4d(p.y, -p.x , 0, 1));
}
// At this point the mat is (N, 1, CV_64FC4)
// Reshape if you want (N, 4, CV_64FC1);
features_1 = features_1.reshape(1,4);
cout << features_1;
}
This output of this is:
[1, 2, 1, 0;
2, -1, 0, 1;
3, 4, 1, 0;
4, -3, 0, 1]
However, if the features_1 is already allocated and you can't just use push_back, apart from releasing the mat, you could do this (assuming features_1.isContinuous() is true):
#include <iostream>
#include <vector>
using namespace std;
#include <opencv2/core/core.hpp>
using namespace cv;
int main()
{
vector<Point2f> feature1;
feature1.push_back(Point2f(1.0f, 2.0f));
feature1.push_back(Point2f(3.0f, 4.0f));
Mat features_1(2 * feature1.size(), 4, CV_64FC1);
Vec4d* ptr = features_1.ptr<Vec4d>(0);
for(auto p : feature1)
{
*ptr++ = Vec4d(p.x, p.y , 1 , 0);
*ptr++ = Vec4d(p.y, -p.x , 0, 1);
}
cout << features_1 << endl;
}
The above produces the same result as the previous version.
If there is any possibility in the above example that features_1.isContinuous() is false, you can use an iterator to scan features_1:
auto ptr = features_1.begin<double>();
for(auto p : feature1)
{
*ptr++ = p.x;
*ptr++ = p.y;
*ptr++ = 1;
*ptr++ = 0;
*ptr++ = p.y;
*ptr++ = -p.x;
*ptr++ = 0;
*ptr++ = 1;
}

opencv r6010 abort() has been called error in visual studio 2013

I have some code to draw a line between two points on an image which are selected by mouse, and then to display a histogram.
However, when I press q as required by code I get an error saying R6010 abort() has been called and saying VC++ run time error.
Please advise me how I can find this error.
#include <vector>
#include "opencv2/highgui/highgui.hpp"
#include <opencv\cv.h>
#include <iostream>
#include<conio.h>
using namespace cv;
using namespace std;
struct Data_point
{
int x;
unsigned short int y;
};
int PlotMeNow(unsigned short int *values, unsigned int nSamples)
{
std::vector<Data_point> graph(nSamples);
for (unsigned int i = 0; i < nSamples; i++)
{
graph[i].x = i;
graph[i].y = values[i];
}
cv::Size imageSize(5000, 500); // your window size
cv::Mat image(imageSize, CV_8UC1);
if (image.empty()) //check whether the image is valid or not
{
std::cout << "Error : Image cannot be created..!!" << std::endl;
system("pause"); //wait for a key press
return 0;
}
else
{
std::cout << "Good job : Image created successfully..!!" << std::endl;
}
// tru to do some ofesseting so the graph do not hide on x or y axis
Data_point dataOffset;
dataOffset.x = 20;
// we have to mirror the y axis!
dataOffset.y = 5000;
for (unsigned int i = 0; i<nSamples; ++i)
{
graph[i].x = (graph[i].x + dataOffset.x) * 3;
graph[i].y = (graph[i].y + dataOffset.y) / 200;
}
// draw the samples
for (unsigned int i = 0; i<nSamples - 1; ++i)
{
cv::Point2f p1;
p1.x = graph[i].x;
p1.y = graph[i].y;
cv::Point2f p2;
p2.x = graph[i + 1].x;
p2.y = graph[i + 1].y;
cv::line(image, p1, p2, 'r', 1, 4, 0);
}
cv::namedWindow("MyWindow1", CV_WINDOW_AUTOSIZE); //create a window with the name "MyWindow"
cv::imshow("MyWindow1", image); //display the image which is stored in the 'img' in the "MyWindow" window
while (true)
{
char c = cv::waitKey(10);
if (c == 'q')
break;
}
destroyWindow("MyWindow1");
destroyWindow("MyWindow"); //destroy the window with the name, "MyWindow"
return 0;
}
void IterateLine(const Mat& image, vector<ushort>& linePixels, Point p2, Point p1, int* count1)
{
LineIterator it(image, p2, p1, 8);
for (int i = 0; i < it.count; i++, it++)
{
linePixels.push_back(image.at<ushort>(it.pos())); //doubt
}
*count1 = it.count;
}
//working line with mouse
void onMouse(int evt, int x, int y, int flags, void* param)
{
if (evt == CV_EVENT_LBUTTONDOWN)
{
std::vector<cv::Point>* ptPtr = (std::vector<cv::Point>*)param;
ptPtr->push_back(cv::Point(x, y));
}
}
void drawline(Mat image, std::vector<Point>& points)
{
cv::namedWindow("Output Window");
cv::setMouseCallback("Output Window", onMouse, (void*)&points);
int X1 = 0, Y1 = 0, X2 = 0, Y2 = 0;
while (1)
{
cv::imshow("Output Window", image);
if (points.size() > 1) //we have 2 points
{
for (auto it = points.begin(); it != points.end(); ++it)
{
}
break;
}
waitKey(10);
}
//just for testing that we are getting pixel values
X1 = points[0].x;
X2 = points[1].x;
Y1 = points[0].y;
Y2 = points[1].y;
// Draw a line
line(image, Point(X1, Y1), Point(X2, Y2), 'r', 2, 8);
cv::imshow("Output Window", image);
//exit image window
while (true)
{
char c = cv::waitKey(10);
if (c == 'q')
break;
}
destroyWindow("Output Window");
}
void show_histogram_image(Mat img1)
{
int sbins = 65536;
int histSize[] = { sbins };
float sranges[] = { 0, 65536 };
const float* ranges[] = { sranges };
cv::MatND hist;
int channels[] = { 0 };
cv::calcHist(&img1, 1, channels, cv::Mat(), // do not use mask
hist, 1, histSize, ranges,
true, // the histogram is uniform
false);
double maxVal = 0;
minMaxLoc(hist, 0, &maxVal, 0, 0);
int xscale = 10;
int yscale = 10;
cv::Mat hist_image;
hist_image = cv::Mat::zeros(65536, sbins*xscale, CV_16UC1);
for int s = 0; s < sbins; s++)
{
float binVal = hist.at<float>(s, 0);
int intensity = cvRound(binVal * 65535 / maxVal);
rectangle(hist_image, cv::Point(s*xscale, hist_image.rows),
cv::Point((s + 1)*xscale - 1, hist_image.rows - intensity),
cv::Scalar::all(65535), 1);
}
imshow("Histogram", hist_image);
waitKey(0);
}
int main()
{
vector<Point> points1;
vector<ushort>linePixels;
Mat img = cvLoadImage("desert.jpg");
if (img.empty()) //check whether the image is valid or not
{
cout << "Error : Image cannot be read..!!" << endl;
system("pause"); //wait for a key press
return -1;
}
//Draw the line
drawline(img, points1);
//now check the collected points
Mat img1 = cvLoadImage("desert.jpg");
if (img1.empty()) //check whether the image is valid or not
{
cout << "Error : Image cannot be read..!!" << endl;
system("pause"); //wait for a key press
return -1;
}
int *t = new int;
IterateLine( img1, linePixels, points1[1], points1[0], t );
PlotMeNow(&linePixels[0], t[0]);
show_histogram_image(img);
delete t;
_getch();
return 0;
}
This is one of the bad smells in your code:
void IterateLine(const Mat& image, vector<ushort>& linePixels, Point p2, Point p1, int* count1)
{
...
linePixels.push_back(image.at<ushort>(it.pos())); //doubt
Now image is a CV_8UC3 image (from Mat img1 = cvLoadImage("desert.jpg");, but you are accessing here like it is CV_16UC1, so what gets put in linePixels is garbage. This will almost certainly cause PlotMeNow() to draw outside its image and corrupt something, which is probably why your code is crashing.
Sine it is very unclear what your code is trying to do, I can't suggest what you should have here instead.
I have just managed to do this, you only have to put "-1" to your loop limit:
for (unsigned int i = 0; i < nSamples-1; i++)
{
graph[i].x = i;
graph[i].y = values[i];
}

Resources