使用像素值或整数时结果的差异

问题描述

在使用Matlab进行图像处理时(通过Fuzzy Logic确实改善了img),我发现了一件非常奇怪的事情。我的模糊函数是正确的,我在随机值上对其进行了测试,它们基本上是简单的线性函数

function f = Udark(z)
if z < 50
    f = 1;
elseif z > 125
    f = 0;
elseif (z >= 50) && (z <= 125)
    f = -z/75 + 125/75;
end

end

其中z是像素值(灰度)。现在发生了一件非常奇怪的事情。 f = -z/75 + 125/75;,其中a是图像。但是,如果将其用作输入,则给出的结果确实不同。即如果我使用变量p = 99,则函数输出应为0.3467,当我使用A(i,j)时,其结果为f=2。由于这显然是不可能的,所以我不知道问题出在哪里。我以为变量的类型可能会出现这种情况,但是如果我将其更改为uint8,它将保持不变...如果您知道发生了什么,请告诉我:)

解决方法

1。换行:

f = (125/75) - (z/75);

在编辑第三个条件后,结果/转换后的图像的像素值不为2。不确定是否要使用小数。如果需要使用小数,请使用im2double()函数来转换图像并将其放大255倍即可满足您的需求。四舍五入请参见标题3。

2。阅读图像并进行测试:

%Reading in the image and applying the function%
Image = imread("RGB_Image.png");
Greyscale_Image = rgb2gray(Image);

[Image_Height,Image_Width] = size(Greyscale_Image);
Transformed_Image = zeros(Image_Height,Image_Width);

for Row = 1: +1: Image_Height
   for Column = 1: +1: Image_Width 
    
    Pixel_Value = Greyscale_Image(Row,Column);
    [Transformed_Pixel_Value] = Udark(Pixel_Value);
    Transformed_Image(Row,Column) = Transformed_Pixel_Value;
   
   end 
end

subplot(1,2,1); imshow(Greyscale_Image);
subplot(1,2); imshow(Transformed_Image);

%Checking that no transformed pixels falls in this impossible range%
Check = (Transformed_Image > (125/75)) & (Transformed_Image ~= 1);
Check_Flag = any(Check,'all');


%Function to transform pixel values%
function f = Udark(z)
if z < 50
    f = 1;
elseif z > 125
    f = 0;
elseif (z >= 50) && (z <= 125)
    f = (125/75) - (z/75);
end

end

3。评估第三个条件的细节

使用整数(uint8)将强制将值四舍五入为最接近的整数。介于范围(50,125)之间的任何数字都将取值为1或0。

f = -z/75 + 125/75;

如果z = 50.1,

-50.1 / 75 + 125/75 = 74.9 / 75≈0.9987→舍入为1

使用MATLAB版本:R2019b