opencvsharp icon indicating copy to clipboard operation
opencvsharp copied to clipboard

Operator '+' cannot applied to int and Mat

Open holzhawi opened this issue 1 year ago • 3 comments

Summary of your issue

After update dotnet SDK from 6.0 to 8.0 and OpenCvSharp4 from 4.7.0 to 4.10.0 visual studio shows compiler error CS0019: Operator '+' cannot applied to int and Mat. It also does'nt work with operator '-'.

Environment

Im using Visual Studio 2022 (Version 17.9.3) with SKD dotnet 8.0.302 and OpenCvSharp 4.10.0

What did you do when you faced the problem?

Writing code...

Example code:

using var img1 = Cv2.ImRead(@"..\..\..\Images\ImageTop1.png", ImreadModes.Grayscale);
using var img2 = Cv2.ImRead(@"..\..\..\Images\ImageTop2.png", ImreadModes.Grayscale);

using var diff = (255 + img2 - img1)/2;

Output:

Error	CS0019	Operator '+' cannot be applied to operands of type 'int' and 'Mat'

What did you intend to be?

I tried to get a difference image with positive and negative values normalized to range [0..255].

holzhawi avatar Jul 15 '24 13:07 holzhawi

With the same environment and OpenCvSharp 4.7.0 it works fine. The error occurs after update to 4.10.0.

holzhawi avatar Jul 15 '24 14:07 holzhawi

https://github.com/shimat/opencvsharp/pull/1677/files#diff-f83edd25b2997a3130e07dd6a64e7fb485a6c82abd2c6120fd3de7f5ebf79b9dR172

This is because I disabled the implicit conversion from double to Scalar. The introduction of the nint type in the new .NET made it easy to get confused between numeric literals, and I made this painful decision because of unintended behavior in the Mat constructor overloading resolution. I believe this problem can be solved by changing the code as follows:

using var diff = (new Scalar(255) + img2 - img1) / new Scalar(2);

shimat avatar Jul 16 '24 02:07 shimat

Dividing by Scalar leads to the same error: Operator '/' cannot be applied to operands of type 'MatExpr' and 'Scalar' I found that the operators '*' and '/' are still working as usual. The following solution works for me:

using var diff = (new Scalar(255) + img2 - img1) / 2;

holzhawi avatar Jul 16 '24 06:07 holzhawi

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Apr 26 '25 01:04 stale[bot]