Why won't this work; opencv Mat_<float> - c++

I can't seem to get this to work. I'm trying to get the pixel value of an image but first need to change the color of the image, but since I cannot use int or just Mat because the values are not whole numbers, I have to use <float> and because of that errors pop up when I try to run this on the cmd.
int main(int argc, char **argv)
{
Mat img = imread(argv[1]);
ofstream myfile;
Mat_<float> MatBlue = img;
int rows1 = MatBlue.rows;
int cols1 = MatBlue.cols;
for(int x = 0; x < cols1; x++) {
for(int y = 0; y < rows1; y++) {
float val = MatBlue.at<cv::Vec3b>(y, x)[1];
MatBlue.at<cv::Vec3b>(y, x)[0] = val + 1;
}
}
}

To achieve your goal, i.e. type conversion, use cv::Mat::convertTo.
Example: img.convertTo(MatBlue, CV_32F) or img.convertTo(MatBlue, CV_32F, 1.0/255.0) (to have values normalized between 0 and 1).
You are mixing char and float pointer types in your code.

Related

Coding dedicated function Average Filter to color Images C++ OpenCV

So basically, I have to code my own function in C++ with OpenCV, that will apply average filter on both gray and color images.
The function returns a Mat Object, have a mat Object and the size of the average filter (3 for 3x3 matrix of filtering for example).
I did this for the moment, it doesn't work, and I don't know how to extend it to color.
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
Mat filtrageMoyen(Mat image, int tailleZonage) {
Mat imageRetour;
imageRetour = image.clone();
Scalar intensite = 0;
int cadrillage = tailleZonage / 2;
int valeurMoyenne = 0;
for (size_t x = 0; x < imageRetour.rows; x++)
{
for (size_t y = 0; y < imageRetour.cols; y++)
{
for (size_t xZonage = 0; xZonage < cadrillage; xZonage++)
{
for (size_t yZonage = 0; yZonage < cadrillage; yZonage++)
{
valeurMoyenne += (image.at<unsigned char>(x+xZonage, y + yZonage));
}
}
imageRetour.at<unsigned char>(x, y) = valeurMoyenne;
valeurMoyenne = 0;
}
}
return imageRetour;
}
int main() {
Mat img;
string filename = "imageRickRoll.png";
img = imread(filename, cv::IMREAD_GRAYSCALE);
imshow("Image filtree", filtrageMoyen(img, 5));
waitKey(0);
return 0;
}

Create a single image from images array

Hi I'm trying to create a single image from multiple images in opencv.
images I use are the same size.
what I do is reshaping them to single line and then try to merge them together with my new image.
I create new image with size of 2 images and pass the array but I recieve error EXC_BAD_ACCESS(code=1, address = ..)
note: sizes of images are correct
size of single image : [170569 x 1]
size of new_image : [170569 x 2]
my code is below.
thank you
int main(){
Mat image[2];
image[0]= imread("image1.jpg",0);
image[1]= imread("image2.jpg",0);
image[0] = image[0].reshape(0, 1); //SINGLE LINE
image[1] = image[1].reshape(0, 1); //SINGLE LINE
int size = sizeof(image)/sizeof(Mat);
Mat new_image(image[0].cols,size,CV_32FC1,image);
}
Mat new_image;
vconcat(image[0],image[1],new_image);
If I understand well than you need to concatenate 2 image of same size into one Mat. I wrote this a very quick code to perform this task.
U can change the argument to the function to be a pointer and add other handlers to care about the variant size image.
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
cv::Mat cvConcatenateMat(const cv::Mat &image1, const cv::Mat &image2, bool isCol CV_DEFAULT(true)){
if (isCol) {
cv::Mat mergeMat = cv::Mat(image1.rows, image1.cols + image2.cols, image1.type());
for (int j = 0; j < image1.rows; j++) {
for (int i = 0; i < image1.cols; i++) {
mergeMat.at<cv::Vec3b>(j,i) = image1.at<cv::Vec3b>(j,i);
}
for (int i = image1.cols; i < mergeMat.cols; i++) {
mergeMat.at<cv::Vec3b>(j,i) = image2.at<cv::Vec3b>(j,i);
}
}
return mergeMat;
} else {
cv::Mat mergeMat = cv::Mat(image1.rows + image2.rows, image1.cols, image1.type());
for (int j = 0; j < image1.cols; j++) {
for (int i = 0; i < image1.rows; i++) {
mergeMat.at<cv::Vec3b>(i,j) = image1.at<cv::Vec3b>(i,j);
}
for (int i = image1.rows; i < mergeMat.rows; i++) {
mergeMat.at<cv::Vec3b>(i,j) = image2.at<cv::Vec3b>(i-image1.rows,j);
}
}
return mergeMat;
}
}
int main(int argc, const char * argv[]) {
cv::Mat image1 = cv::imread("img1.jpg");
cv::Mat image2 = cv::imread("img2.jpg");
cv::resize(image2, image2, image1.size());
cv::Mat outImage = cvConcatenateMat(image1, image2, false);
cv::imshow("out image", outImage);
cv::waitKey(0);
return 0;
}

OpenCV fast mat element and neighbour access

I use OpenCV (C++) Mat for my matrix and want to acces single Mat elements as fast as possible. From OpenCV tutorial, I found code for efficient acces:
for( i = 0; i < nRows; ++i)
{
p = I.ptr<uchar>(i);
for ( j = 0; j < nCols; ++j)
{
p[j] = table[p[j]];
}
}
For my problem, I need to access a Mat element and its neighbours (i-1,j-1) for a calculation. How can I adapt the given code to acces a single mat element AND its surrounding elements? Since speed matters, I want to avoid Mat.at<>().
What is the most efficient way to acces a Mat value and its neighbour values?
The pixel and its neighbor pixels can be formed a cv::Rect, then you can simply use:
cv::Mat mat = ...;
cv::Rect roi= ...; // define it properly based on the neighbors defination
cv::Mat sub_mat = mat(roi);
In case your neighbors definition is not regular, i.e. they cannot form a rectangle area, use mask instead. Check out here for examples.
You can directly refers to Mat::data:
template<class T, int N>
T GetPixel(const cv::Mat &img, int x, int y) {
int k = (y * img.cols + x) * N;
T pixel;
for(int i=0;i<N;i++)
pixel[i] = *(img.data + k + i);
return pixel;
}
template<class T,int N>
void SetPixel(const cv::Mat &img, int x, int y, T t) {
int k = (y * img.cols + x) * N;
for(int i=0;i<N;i++)
*(img.data + k + i) = t[i];
}
template<>
unsigned char GetPixel<unsigned char, 1>(const cv::Mat &img, int x, int y) {
return *(img.data + y * img.cols + x);
}
template<>
void SetPixel<unsigned char, 1>(const cv::Mat &img, int x, int y, unsigned char p) {
*(img.data + y * img.cols + x) = p;
}
int main() {
unsigned char r,g,b;
int channels = 3;
Mat img = Mat::zeros(256,256, CV_8UC3);
for(int x=0;x<img.cols;x+=2)
for(int y=0;y<img.rows;y+=2)
SetPixel<cv::Vec3b, 3>(img, x, y, cv::Vec3b(255,255,255));
Mat imgGray = Mat::zeros(256,256, CV_8UC1);
for(int x=0;x<imgGray.cols;x+=4)
for(int y=0;y<imgGray.rows;y+=4)
SetPixel<unsigned char, 1>(imgGray, x, y, (unsigned char)255);
imwrite("out.jpg", img);
imwrite("outGray.jpg", imgGray);
return 0;
}
That is pretty fast I think.
out.jpg:
outGray.jpg:
For any future readers: Instead of reading the answers here, please read this blog post https://www.learnopencv.com/parallel-pixel-access-in-opencv-using-foreach/ for a benchmark-based analysis of this functionality, as some of the answers are a bit off the bat.
From that post you can see that the fastest way to access pixels is using the forEach C++ Mat function. If you want the neighborhood it depends of the size; if you're looking for the usual squared 3x3 neighborhood, use pointers like this:
Mat img = Mat(100,100,CV_8U, Scalar(124)); // sample mat
uchar *up, *row, *down; // Pointers to rows
uchar n[9]; // neighborhood
for (int y = 1 ; y < (img.rows - 1) ; y++) {
up = img.ptr(y - 1);
row = img.ptr(y);
down = img.ptr(y + 1);
for (int x = 1 ; x < (img.cols - 1) ; x++) {
// Examples of how to access any pixel in the 8-connected neighborhood
n[0] = up[x - 1];
n[1] = up[x];
n[2] = up[x + 1];
n[3] = row[x - 1];
n[4] = row[x];
n[5] = row[x + 1];
n[6] = down[x - 1];
n[7] = down[x];
n[8] = down[x + 1];
}
}
This code can still be optimized but the idea of using row pointers is what I was trying to convey; this is just a bit faster than using the .at() function and you might have to do benchmarking to notice the difference (in versions of OpenCV 3+). You might want to use .at() before deciding to optimize pixel access.

Contrast & brightness of images using IplImage

Please have a look at the following code
using namespace cv;
double alpha = 1.6;
int beta = 50;
int i = 0;
IplImage* input_img = cvLoadImage("c:\\Moori.jpg", CV_LOAD_IMAGE_GRAYSCALE);
IplImage* imageGray = cvCreateImage(cvSize(input_img->width, input_img->height), IPL_DEPTH_8U, 1);
for( int y = 0; y < input_img->height; y++ )
{
for( int x = 0; x < input_img->width; x++ )
{
i = y * imageGray->width + x;
imageGray->imageData[i] = (alpha * input_img->imageData[i]) + beta;
}
}
cvNamedWindow("Image IplImage", 1);
cvShowImage("Image IplImage", imageGray);
waitKey();
cvReleaseImage(&imageGray);
cvReleaseImage(&input_img);
cvDestroyWindow("Image IplImage");
when I run this code, it shows an image with many dark pixels.
But, when i run the code, which is available at:
http://docs.opencv.org/doc/tutorials/core/basic_linear_transform/basic_linear_transform.html
it works fine. I want to do by IplImage. Please help
saturate_cast is for c++.
http://docs.opencv.org/modules/core/doc/intro.html
Finally, I have solved this problem.
IplImage* img;
cvNamedWindow("Display");
while(true)
{
img = cvLoadImage("Moori.jpg");
CvScalar brVal = cvScalarAll(abs(10.0));
cvAddS(img, brVal, img, NULL);
IplImage *pTempImg = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, img->nChannels);
cvSet( pTempImg, cvScalarAll(1), NULL );
double scale = 1.5;
cvMul(img, pTempImg, img, scale);
cvReleaseImage(&pTempImg);
cvShowImage("Display", img);
cvReleaseImage(&img);
int c=cvWaitKey(10);
if(c==27) break;
}
cvDestroyWindow("Display");
You dont have to cast the image values to uchar. You have to reinterpret the values as uchar. It Means you have to assume that the data bits actually represent an unsigned char, regardless of the type of pointer. It can be done as follows:
uchar* ptr = reinterpret_cast<uchar*>(imageGray->imageData);
ptr[i] = saturate_cast<uchar>(alpha * ptr[i] + beta);
If you are using C++ I am not sure why anybody would want to use IplImage. But your problem is this line
imageGray->imageData[i] = (alpha * input_img->imageData[i]) + beta;
It can overflow. Also imageData is a char*, and a char may be signed or unsigned, you need to make it unsigned. You need use saturate_cast to prevent overflow, and a cast to get rid of the signed char:
imageGray->imageData[i] = saturate_cast<uchar>((alpha * static_cast<uchar>(input_img->imageData[i])) + beta);
You can use this little program to see what is going on:
#include <opencv2/core/core.hpp>
#include <iostream> // std::cout
#include <vector> // std::vector
int main(int argc, char** argv)
{
double alpha = 1.6;
int beta = 50;
std::vector<uchar> z;
for(int i = 0; i <= 255; ++i)
z.push_back(i);
char* zp = reinterpret_cast<char *>(&z[0]);
for(int i = 0; i <= 255; ++i)
std::cout << i << " -> " << int(cv::saturate_cast<uchar>(alpha * static_cast<uchar>(zp[i]) + beta)) << std::endl;
}

Why does assertion fail here

Why does the assertion fail here when i create a CvMat *? It does not happen with an image i load in cv::Mat using a pointer.
struct RGB { unsigned char b, g, r; };
cv::Point p;
RGB *data;
CvMat* mat = cvCreateMat(300,300,CV_32FC1);
for( row = 0; row < mat->rows; ++row)
{
for ( col = 0; col < mat->cols; ++col)
{
p.x=row,p.y=col;
ERROR ----->>> assert((mat->step/mat->cols) == sizeof(RGB));
data = (RGB*)&mat->data;
data += p.y * mat->cols + p.x;
}
}
For this code the assertion does not fail:
IplImage * img=cvLoadImage("blah.jpg");
int row=0,col=0;
cv::Mat in(img);
cv::Mat *mat=&in;
cv::Point p;
struct RGB { unsigned char b, g, r; };
RGB *data;
for( row = 0; row < mat->rows; ++row)
{
for ( col = 0; col < mat->cols; ++col)
{
p.x=row,p.y=col;
assert((mat->step/mat->cols) == sizeof(RGB));
data = (RGB*)&mat->data;
data += p.y * mat->cols + p.x;
printf("Row=%dxCol=%d b=%u g=%u r=%u\n",row,col,data->b,data->g,data->r);
wait_for_frame(1);
}
}
Because sizeof(RGB) != sizeof(float), which is what you filled the matrix with here:
CvMat* mat = cvCreateMat(300,300,CV_32FC1);
CV_32FC1 means 1 component, 32-bit floating point. You probably want CV_8UC3. See here or another OpenCV reference.
You can skip the entire IplImage misery if you use
cv::Mat img = cv::loadImage("blah.jpg");
Also it is better to use row ptr for going through all the pixels.
It knows the jumps, so you don't have to worry!
From the refman:
If you need to process a whole row of a 2D array, the most efficient
way is to get the pointer to the row first, and then just use the
plain C operator []
Be aware that if you are loading bigger images which have "jumps" in their data, your code will not work.
In your situation
cv::Mat img = cv::loadImage("blah.jpg");
const cv::Mat& M = img;
for(int i = 0; i < rows; i++)
{
const Vec3b* Mi = M.ptr<Vec3b>(i);
for(int j = 0; j < cols; j++)
{
const Vec3b& Mij = Mi[j];
std::cout<<"Row="<<i<<"Col="<<j<<"\t";
std::cout<<"b="<<Mij[0]<<" g="<<Mij[1]<<" r="<<Mij[2]<<std::endl;
}
}
is the fastest correct way. Otherwise you could use M.at<Vec3b>(i,j).