shimat / opencvsharp

OpenCV wrapper for .NET
Apache License 2.0
5.33k stars 1.15k forks source link

Operator '+' cannot applied to int and Mat #1684

Open holzhawi opened 1 month ago

holzhawi commented 1 month ago

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 commented 1 month ago

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

shimat commented 1 month ago

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);
holzhawi commented 1 month ago

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;