问题
I want to copy a center part (Rectangle) of my image to a completely white Mat
(to the same position).
Code:
Mat src = Image.Mat;
Mat dst = new Mat(src.Height, src.Width, DepthType.Cv8U, 3);
dst.SetTo(new Bgr(255, 255, 255).MCvScalar);
Rectangle roi = new Rectangle((int)(0.1 * src.Width), (int)(0.1 * src.Height), (int)(0.8 * src.Width), (int)(0.8 * src.Height));
Mat srcROI = new Mat(src, roi);
Mat dstROI = new Mat(dst, roi);
srcROI.CopyTo(dstROI);
//I have dstROI filled well. CopyTo method is doing well.
//However I have no changes in my dst file.
However I'm getting only white image as a result - dst
. Nothing inside.
What i'm doing wrong?
using EmguCV 3.1
EDIT
I have a dstROI
Mat filled well. But there is a problem how to apply changes to original dst
Mat now.
Changing CopyTo
like this:
srcROI.CopyTo(dst);
causes that dst is filled now with my part of src image but not in the centre like i wanted
EDIT 2
src.Depth = Cv8U
As you suggested I check a value of IsSubmatrix
property.
Console.WriteLine(dstROI.IsSubmatrix);
srcROI.CopyTo(dstROI);
Console.WriteLine(dstROI.IsSubmatrix);
gives output:
true
false
What can be wrong then?
回答1:
According to the operator precedence rules of C# a type cast has higher priority than multiplication.
Hence (int)0.8 * src.Width
is equivalent to 0 * src.Width
, and the same applies to the other parameters of the roi
rectangle. Therefore the line where you create the roi
is basically
Rectangle roi = new Rectangle(0,0,0,0);
Copying a 0-size block does nothing, so you're left with the pristine white image you created earlier.
Solution
Parenthesize your expressions properly.
Rectangle roi = new Rectangle((int)(0.1 * src.Width)
, (int)(0.1 * src.Height)
, (int)(0.8 * src.Width)
, (int)(0.8 * src.Height));
回答2:
Ancient question, I know, but it came up when I searched so an answer here might still be being hit in searches. I had a similar issue and it may be the same problem. If src
and dst
have different numbers of channels or different depths, then a new Mat
is created instead. I see that they both have the same depth, but in my case, I had a single channel going into a 3 channel Mat
. If your src
is not a 3 channel Mat
, then this may be the issue (it might be 1 (gray) or 4 channel (BGRA) for example).
来源:https://stackoverflow.com/questions/37335774/copy-part-of-image-to-another-image-with-emgucv