copying non-rectangular roi opencv - c++

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]

Related

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

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;

Create a transparent image in opencv

I am trying to rotate an image in x, y and z axis as in this.
The image should not be cropped while rotating So I am doing this
Mat src = imread("path");
int diagonal = (int)sqrt(src.cols*src.cols+src.rows*src.rows);
int newWidth = diagonal;
int newHeight =diagonal;
Mat targetMat(newWidth, newHeight, src.type());
I am creating a bigger image targetMat. The input image is a png image.
But I want this image as a transparent image. So I tried this
Mat targetMat(newWidth, newHeight, src.type(), cv::Scalar(0,0,0,0));
But the output image was
What I need is (Transparent image is here)
So what change do I have to do?
The problem is, that your input image is type CV_8UC3 but you need CV_8UC4 to use the alpha channel. So try Mat targetMat(newHeight, newWidth, CV_8UC4, cv::Scalar(0,0,0,0)); or cvtColor of src before creation of new mat
To use your original image, there are two possibilities:
use cv::cvtColor(src, src, CV_BGR2BGRA) (and adjust later code to use a 4 channel matrix - cv::Vec4b instead of cv::Vec3b etc)
if your input file is a .png with alpha channel you can use the CV_LOAD_IMAGE_ANYDEPTH (hope this is the right one) flag to load it as a CV_xxC4 image (might be 16 bit too) and to use the original alpha values.

How to draw rectangle with mask image in opencv?

Mask image
Result image
Expected image
Is there any function to draw a rectangle with mask image using opencv? i have attached the expected image. Please help me. thanks in advance.
I think your asked question isn't quite clear, but if the first image is your original image (circle), the second one (rectangle) is your binary mask image, and you want to apply that mask on the original image, than you can apply the mask as followed:
inputMat.copyTo(outputMat, maskMat);
Src.: https://stackoverflow.com/a/18161322/4767895
If you haven't already created a binary mask, do it this way:
Create a mask with the same size as your original image (set all zero), and draw a filled rectangle (set all one) with specific size in it.
cv::Mat mask = cv::Mat::zeros(Rows, Cols, CV_8U); // all 0
mask(Rect(StartX,StartY,Width,Height)) = 1; //make rectangle 1
Src.: https://stackoverflow.com/a/18136171/4767895
Feel free to response if I misunderstood your question.
Try using Boolean Operation provided in Opencv
Please refer to this code (source). I have added all the bitwise operation in case you need any.
int main( )
{
Mat drawing1 = Mat::zeros( Size(400,200), CV_8UC1 );
Mat drawing2 = Mat::zeros( Size(400,200), CV_8UC1 );
drawing1(Range(0,drawing1.rows),Range(0,drawing1.cols/2))=255; imshow("drawing1",drawing1);
drawing2(Range(100,150),Range(150,350))=255; imshow("drawing2",drawing2);
Mat res;
bitwise_and(drawing1,drawing2,res); imshow("AND",res);
bitwise_or(drawing1,drawing2,res); imshow("OR",res);
bitwise_xor(drawing1,drawing2,res); imshow("XOR",res);
bitwise_not(drawing1,res); imshow("NOT",res);
waitKey(0);
return(0);
}

Getting masked area to be transparent?

So far i have managed to use masks and get the second image from the first. But what i want is the black area in second image to be transparent (i.e the output i an trying to get is the third image) Here is the code so far. Please advice me on this.
EDIT: Third one is from photoshop
//imwrite parameters
compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
compression_params.push_back(100);
//reading image to be masked
image = imread(main_img, -1);
//CV_LOAD_IMAGE_COLOR
namedWindow("output", WINDOW_NORMAL);
//imshow("output", image);
//Creating mask image with same size as original image
Mat mask(image.rows, image.cols, CV_8UC1, Scalar(0));
// Create Polygon from vertices
ROI_Vertices.push_back(Point2f(float(3112),float(58)));
ROI_Vertices.push_back(Point2f(float(3515),float(58)));
ROI_Vertices.push_back(Point2f(float(3515),float(1332)));
ROI_Vertices.push_back(Point2f(float(3112),float(958)));
approxPolyDP(ROI_Vertices, ROI_Poly, 1, true);
// Fill polygon white
fillConvexPoly(mask, &ROI_Poly[0] , ROI_Poly.size(), 255, 8, 0);
//imshow("output", mask);
// Create new image for result storage
imageDest = cvCreateMat(image.rows, image.cols, CV_8UC4);
// Cut out ROI and store it in imageDest
image.copyTo(imageDest, mask);
imwrite("masked.jpeg", imageDest, compression_params);
imshow("output", imageDest);
cvWaitKey(0);
This can be done by first setting its alpha value to 0 of the regions that you want to make them fully transparent (255 for others), and then save it to PNG.
To set the alpha value of pixel-(x,y), it can be done:
image.at<cv::Vec4b>(y, x)[3] = 0;
PS: you need to convert it to 4-channel format first if the image is not currently. For example:
cv::cvtColor(image, image, CV_BGR2BGRA);
Updated: It will be easier if you have already computed the mask for the ROI region, where you can simply merge it with the original image (assume having 3 channels) to get the final result. Like:
cv::Mat mask; // 0 for transparent regions, 255 otherwise (serve as the alpha channel)
std::vector<cv::Mat> channels;
cv::split(image, channels);
channels.push_back(mask);
cv::Mat result;
cv::merge(channels, result);

copying ipl image pixel by pixel

The problem is solved....I used cvGet2D,below is the sample code
CvScalar s;
s=cvGet2D(src_Image,pixel[i].x,pixel[i].y);
cvSet2D(dst_Image,pixel[i].x,pixel[i].y,s);
Where src_Iamge and dst_Image is the source and destination image correspondingly and pixel[i] is the selected pixel i wanted to draw in the dst image. I have include the real out image below.
have an source Ipl image, I want to copy some of the part of the image to a new destination image pixel by pixel. can any body tell me how can do it? I use c,c++ in opencv. For example if the below image is source image,
The real output image
EDIT:
I can see the comments suggesting cvGet2d. I think, if you just want to show "points", it is best to show them with a small neighbourhood so they can be seen where they are. For that you can draw white filled circles with origins at (x,y), on a mask, then you do the copyTo.
using namespace cv;
Mat m(input_iplimage);
Mat mask=Mat::zeros(m.size(), CV_8UC1);
p1 = Point(x,y);
r = 3;
circle(mask,p1,r, 1); // draws the circle around your point.
floodFill(mask, p1, 1); // fills the circle.
//p2, p3, ...
Mat output = Mat::zeros(m.size(),m.type()); // output starts with a black background.
m.copyTo(output, mask); // copies the selected parts of m to output
OLD post:
Create a mask and copy those pixels:
#include<opencv2/opencv.hpp>
using namespace cv;
Mat m(input_iplimage);
Mat mask=Mat::zeros(m.size(), CV_8UC1); // set mask 1 for every pixel you wanna copy.
Rect roi=Rect(x,y,width,height); // create a rectangle
mask(roi) = 1; // set it to 0.
roi = Rect(x2,y2,w2,h2);
mask(roi)=1; // set the second rectangular area for copying...
Mat output = 100*Mat::ones(m.size(),m.type()); // output with a gray background.
m.copyTo(output, mask); // copy selected areas of m to output
Alternatively you can copy Rect-by-Rect:
Mat m(input_iplimage);
Mat output = 100*Mat::ones(m.size(),m.type()); // output with a gray background.
Rect roi=Rect(x,y,width,height);
Mat m_temp, out_temp;
m_temp=m(roi);
out_temp = output(roi);
m_temp.copyTo(out_temp);
roi=Rect(x2,y2,w2,h2);
Mat m_temp, out_temp;
m_temp=m(roi);
out_temp = output(roi);
m_temp.copyTo(out_temp);
The answer to your question only requires to have look at the OpenCV documentation or just to search in your favourite search engine.
Here you've an answer for Ipl images and for newer Mat data.
For having an output as I see in your images, I'd do it setting ROI's, it's more efficient.