Opencv C++ grayscale image black pixeled result (when replacing image values) - c++

I'm new in opencv and I had this problem...
Given the following Mat type (globally declarated)
Mat src_gray;
Mat dst;
I have dst being a zero grayscale Mat with this initialization
dst=Mat::zeros(src_gray.size(), CV_BGR2GRAY);
It seems I can't edit the pixels on the dst image (when I use imwrite, it gives me a black image as if I hadn't done anything).
This is the code I currently have:
for(int i=0;i<=dst.cols;i++)
for(int j=0;j<=dst.rows;j++)
{
dst.at<uchar>(j,i)=255;
}
imwrite( "img_res.png", dst );
The result Image has the dimensions it's supposed to have, but it is a black pixeled picture, shouldn't it be a white pixeled Image?
I don't know if it is relevant if I mention that I have 3 global Mats
Mat image;
Mat src_gray;
Mat dst;
Which are initialized this way:
image = imread( argv[1], 1 );
cvtColor( image, src_gray, CV_BGR2GRAY );
Then, I release them as:
image.release();
dst.release();
src_gray.release();
The other problem I get is that when I release the Mats (during execution), I get the "Segmentation fault (core dumped)" error. (I code from Linux Ubuntu distri)

Try:
dst=Mat::zeros(src_gray.size(), CV_8UC1);
When you use CV_BGR2GRAY, you are creating a Mat with 3 color channels, then, it's not possible to assign a number when you have an array of numbers (B,G,R).
With CV_8UC1, you create a Mat with 1 color channel of uchar then it should works with:
dst.at<uchar>(j,i)=255;

Related

Split frames obtained from video into separate channels

I am trying to read a video (mp4) frame by frame and then convert the frames from BGR to HSV.
I then want to split the HSV Mats into different channels (Hue, Saturation, Value).
this, however, does not work:
void colorize () {
VideoCapture cap("myFile.mp4");
Mat frame;
Mat frame2;
while (true) {
cap>>frame;
cvtColor(frame, frame2, CV_BGR2HSV);
Vector<Mat> channels;
split(frame2, channels);
}
}
The split-function gives the following error:
no matching function for call to ‘split(cv::Mat&, cv::Vector<cv::Mat>&)’
split(frame2, channels);
I have tried the exact same code outside of a loop with another image I had before transformed to hsv and it worked fine, so I assume the problem must be the looping.
Any ideas?
You're using cv::Vector, while instead you should use std::vector (note the lowercase v).
std::vector<Mat> channels; // std::vector, not cv::Vector
split(frame2, channels);

Detection of objects in nonuniform illumination in opencv C++

I am performing feature detection in a video/live stream/image using OpenCV C++. The lighting condition varies in different parts of the video, leading to some parts getting ignored while transforming the RGB images to binary images.
The lighting condition in a particular portion of the video also changes over the course of the video. I tried the 'Histogram equalization' function, but it didn't help.
I got a working solution in MATLAB in the following link:
http://in.mathworks.com/help/images/examples/correcting-nonuniform-illumination.html
However, most of the functions used in the above link aren't available in OpenCV.
Can you suggest the alternative of this MATLAB code in OpenCV C++?
OpenCV has the adaptive threshold paradigm available in the framework: http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#adaptivethreshold
The function prototype looks like:
void adaptiveThreshold(InputArray src, OutputArray dst,
double maxValue, int adaptiveMethod,
int thresholdType, int blockSize, double C);
The first two parameters are the input image and a place to store the output thresholded image. maxValue is the thresholded value assigned to an output pixel should it pass the criteria, adaptiveMethod is the method to use for adaptive thresholding, thresholdType is the type of thresholding you want to perform (more later), blockSize is the size of the windows to examine (more later), and C is a constant to subtract from each window. I've never really needed to use this and I usually set this to 0.
The default method for adaptiveThreshold is to analyze blockSize x blockSize windows and calculate the mean intensity within this window subtracted by C. If the centre of this window is above the mean intensity, this corresponding location in the output position of the output image is set to maxValue, else the same position is set to 0. This should combat the non-uniform illumination issue where instead of applying a global threshold to the image, you are performing the thresholding on local pixel neighbourhoods.
You can read the documentation on the other methods for the other parameters, but to get your started, you can do something like this:
// Include libraries
#include <cv.h>
#include <highgui.h>
// For convenience
using namespace cv;
// Example function to adaptive threshold an image
void threshold()
{
// Load in an image - Change "image.jpg" to whatever your image is called
Mat image;
image = imread("image.jpg", 1);
// Convert image to grayscale and show the image
// Wait for user key before continuing
Mat gray_image;
cvtColor(image, gray_image, CV_BGR2GRAY);
namedWindow("Gray image", CV_WINDOW_AUTOSIZE);
imshow("Gray image", gray_image);
waitKey(0);
// Adaptive threshold the image
int maxValue = 255;
int blockSize = 25;
int C = 0;
adaptiveThreshold(gray_image, gray_image, maxValue,
CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY,
blockSize, C);
// Show the thresholded image
// Wait for user key before continuing
namedWindow("Thresholded image", CV_WINDOW_AUTOSIZE);
imshow("Thresholded image", gray_image);
waitKey(0);
}
// Main function - Run the threshold function
int main( int argc, const char** argv )
{
threshold();
}
adaptiveThreshold should be your first choice.
But here I report the "translation" from Matlab to OpenCV, so you can easily port your code. As you see, most of the functions are available both in Matlab and OpenCV.
#include <opencv2\opencv.hpp>
using namespace cv;
int main()
{
// Step 1: Read Image
Mat1b img = imread("path_to_image", IMREAD_GRAYSCALE);
// Step 2: Use Morphological Opening to Estimate the Background
Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(15,15));
Mat1b background;
morphologyEx(img, background, MORPH_OPEN, kernel);
// Step 3: Subtract the Background Image from the Original Image
Mat1b img2;
absdiff(img, background, img2);
// Step 4: Increase the Image Contrast
// Don't needed it here, the equivalent would be cv::equalizeHist
// Step 5(1): Threshold the Image
Mat1b bw;
threshold(img2, bw, 50, 255, THRESH_BINARY);
// Step 6: Identify Objects in the Image
vector<vector<Point>> contours;
findContours(bw.clone(), contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
for(int i=0; i<contours.size(); ++i)
{
// Step 5(2): bwareaopen
if(contours[i].size() > 50)
{
// Step 7: Examine One Object
Mat1b object(bw.size(), uchar(0));
drawContours(object, contours, i, Scalar(255), CV_FILLED);
imshow("Single Object", object);
waitKey();
}
}
return 0;
}

copying non-rectangular roi opencv

I want to copy a part of an image which is not rectangle with C++ opencv. The corner points of the part is known in the image. I want to paste it in a another image in exact location. Can anybody please help me?
The source image and the destination image are of same size.
here is an example of source image, I know p1,p2,p3,p4 and I want to copy that part to a new image.
I already have a destination image. For example the below image is destination image, and I want to paste only the marked part of the source image to the destination image. How can I do it?
And the final output should look something like this one.
Thanks,
First create a mask image using your four co-ordinates.
Now using Mat::copyTo() copy your balck image to source here you can use above mask.
Allocate black image and mask as source size
Mat src=imread("img.png",1);
Mat black(src.rows, src.cols, src.type(), cv::Scalar::all(0));
Mat mask(src.rows, src.cols, CV_8UC1, cv::Scalar(0));
Now create mask image using drawContours, here you should use CV_FILLED for contour thickness.
Like
vector< vector<Point> > co_ordinates;
co_ordinates.push_back(vector<Point>());
co_ordinates[0].push_back(P1);
co_ordinates[0].push_back(P2);
co_ordinates[0].push_back(P3);
co_ordinates[0].push_back(P4);
drawContours( mask,co_ordinates,0, Scalar(255),CV_FILLED, 8 );
Finally copy black image to source using above mask
black.copyTo(src,mask);
See below result,
Edit :
Based on your comment below here is the steps you need to follow
First create Mask image as described above
Copy the the source image to new Mat dst1 using the mask.
Invert your mask and copy destination image to a new Mat dst2
For final result just add up dest1 and dest2 to new Mat.
Suppose you already created mask as above
Copy source to new Mat
Mat dst1;
src.copyTo(dst1,mask);
Now invert Mask and copy destination image to new Mat
Mat dst2;
bitwise_not(mask,mask);
dst.copyTo(dst2,mask);
Get final result by adding both
Mat result=dest1+dest2;
In case your both image are of different size then you can use following code
Here you should use image ROI for copy, create mask etc..
![Mat src=imread("src.png",1);
Mat dst=imread("dest.jpg",1);
int new_w=0;
int new_h=0;
if(src.cols>dst.cols)
new_w=dst.cols;
else
new_w=src.cols;
if(src.rows>dst.rows)
new_h=dst.rows;
else
new_h=src.rows;
Rect rectROI(0,0,new_w,new_h);
Mat mask(new_h, new_w, CV_8UC1, cv::Scalar(0));
Point P1(107,41);
Point P2(507,61);
Point P3(495,280);
Point P4(110,253);
vector< vector<Point> > co_ordinates;
co_ordinates.push_back(vector<Point>());
co_ordinates\[0\].push_back(P1);
co_ordinates\[0\].push_back(P2);
co_ordinates\[0\].push_back(P3);
co_ordinates\[0\].push_back(P4);
drawContours( mask,co_ordinates,0, Scalar(255),CV_FILLED, 8 );
Mat srcROI=src(rectROI);
Mat dstROI=dst(rectROI);
Mat dst1;
Mat dst2;
srcROI.copyTo(dst1,mask);
imwrite("dst1.jpg",dst1);
bitwise_not(mask,mask);
dstROI.copyTo(dst2,mask);
dstROI.setTo(0);
dstROI=dst1+dst2;
imshow("final result",dst);][4]

C++ and OpenCV: Issue Converting Image to grayscale

Here is my code. It's pretty simple.
Mat image = imread("filename.png");
imshow("image", image);
waitKey();
//Image looks great.
Mat image_gray;
image.convertTo(image_gray, CV_RGB2GRAY);
imshow("image", image_gray);
waitKey();
But when I call the image.convertTo(image_gray, CV_RGB2GRAY); line, I get the following error message:
OpenCV Error: Assertion failed (func != 0) in unknown function, file ..\..\..\sr
c\opencv\modules\core\src\convert.cpp, line 1020
Using OpenCV 2.4.3
The method convertTo does not do color conversion.
If you want to convert from BGR to GRAY you can use the function cvtColor:
Mat image_gray;
cvtColor(image, image_gray, CV_BGR2GRAY);
The function cv::Mat::convertTo is not for color conversion. It is for type conversion. The destination image should have same size and number of channels as the source image.
To convert from RGB to Gray, use the function cv::cvtColor.
cv::cvtColor(image,image_gray,CV_RGB2GRAY);
If you need to acquire video (e.g. from a webcam) in Grayscale, you can also set the saturation of the video feed to zero. (Ex. in Python syntax)
capture = cv.CaptureFromCAM(camera_index)
...
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_SATURATION,0)
image.convertTo(image_gray, CV_RGB2GRAY);
This's wrong.Correct one is,
Mat gray_image;
cvtColor(image, gray_image, CV_BGR2GRAY);
Try this.

Convert RGB to Black & White in OpenCV

I would like to know how to convert an RGB image into a black & white (binary) image.
After conversion, how can I save the modified image to disk?
AFAIK, you have to convert it to grayscale and then threshold it to binary.
1. Read the image as a grayscale image
If you're reading the RGB image from disk, then you can directly read it as a grayscale image, like this:
// C
IplImage* im_gray = cvLoadImage("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);
// C++ (OpenCV 2.0)
Mat im_gray = imread("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);
2. Convert an RGB image im_rgb into a grayscale image: Otherwise, you'll have to convert the previously obtained RGB image into a grayscale image
// C
IplImage *im_rgb = cvLoadImage("image.jpg");
IplImage *im_gray = cvCreateImage(cvGetSize(im_rgb),IPL_DEPTH_8U,1);
cvCvtColor(im_rgb,im_gray,CV_RGB2GRAY);
// C++
Mat im_rgb = imread("image.jpg");
Mat im_gray;
cvtColor(im_rgb,im_gray,CV_RGB2GRAY);
3. Convert to binary
You can use adaptive thresholding or fixed-level thresholding to convert your grayscale image to a binary image.
E.g. in C you can do the following (you can also do the same in C++ with Mat and the corresponding functions):
// C
IplImage* im_bw = cvCreateImage(cvGetSize(im_gray),IPL_DEPTH_8U,1);
cvThreshold(im_gray, im_bw, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
// C++
Mat img_bw = im_gray > 128;
In the above example, 128 is the threshold.
4. Save to disk
// C
cvSaveImage("image_bw.jpg",img_bw);
// C++
imwrite("image_bw.jpg", img_bw);
This seemed to have worked for me!
Mat a_image = imread(argv[1]);
cvtColor(a_image, a_image, CV_BGR2GRAY);
GaussianBlur(a_image, a_image, Size(7,7), 1.5, 1.5);
threshold(a_image, a_image, 100, 255, CV_THRESH_BINARY);
I do something similar in one of my blog postings. A simple C++ example is shown.
The aim was to use the open source cvBlobsLib library for the detection
of spot samples printed to microarray slides, but the images have to be
converted from colour -> grayscale -> black + white as you mentioned, in order to achieve this.
A simple way of "binarize" an image is to compare to a threshold:
For example you can compare all elements in a matrix against a value with opencv in c++
cv::Mat img = cv::imread("image.jpg", CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat bw = img > 128;
In this way, all pixels in the matrix greater than 128 now are white, and these less than 128 or equals will be black
Optionally, and for me gave good results is to apply blur
cv::blur( bw, bw, cv::Size(3,3) );
Later you can save it as said before with:
cv::imwrite("image_bw.jpg", bw);
Simple binary threshold method is sufficient.
include
#include <string>
#include "opencv/highgui.h"
#include "opencv2/imgproc/imgproc.hpp"
using namespace std;
using namespace cv;
int main()
{
Mat img = imread("./img.jpg",0);//loading gray scale image
threshold(img, img, 128, 255, CV_THRESH_BINARY);//threshold binary, you can change threshold 128 to your convenient threshold
imwrite("./black-white.jpg",img);
return 0;
}
You can use GaussianBlur to get a smooth black and white image.