Salt and pepper code in matlab

32 ビュー (過去 30 日間)
Rooter Boy
Rooter Boy 2020 年 11 月 10 日
コメント済み: Image Analyst 2020 年 11 月 10 日
I want to convert from this opencv code to matlab code.
My tried code:
% I generated random salt & pepper noise
dim = size(I);
[m, n] = size(I);
saltpepper_noise=zeros((m, n));
saltpepper_noise=rand(m,n); #creates a uniform random variable from 0 to 1
for i in range(0,m):
for j in range(0,n):
if saltpepper_noise[i,j]<=0.5:
saltpepper_noise[i,j]=0
else:
saltpepper_noise[i,j]=255
  1 件のコメント
Nathan Bblanc
Nathan Bblanc 2020 年 11 月 10 日
Not sure I understand your code fully, is I defined before the code begins?
in any case, a few corrections
  • the asignment [m,n]=x is impossible in matlab, you can should define them seperatly:
m=size(I)(1)
n=size(I)(2)
  • no need to define saltpepper_noise twice, you can just use the second line
  • in a for loop, you use the syntax for i=1:m
in general, i suggest you use matlab's online documentation, it's very helpful and full of examples

サインインしてコメントする。

回答 (2 件)

Image Analyst
Image Analyst 2020 年 11 月 10 日
編集済み: Image Analyst 2020 年 11 月 10 日
If you want to use conditionals and be as close as possible to that code (instead of using the built-in imnoise function), then you can do this:
% Get grayscale image
saltpepper_img = imread('cameraman.tif');
[img.rows, img.cols] = size(saltpepper_img);
% Create noise image.
saltpepper_noise = randi(255, img.rows, img.cols, 'uint8');
subplot(2, 2, 1);
imshow(saltpepper_noise);
title('Original Noise', 'FontSize', 15);
black = saltpepper_noise < 10;
subplot(2, 2, 2);
imshow(black);
title('Black Locations', 'FontSize', 15);
white = saltpepper_noise > 245;
subplot(2, 2, 3);
imshow(white);
title('White Locations', 'FontSize', 15);
% Assign black and white to gray scale image.
saltpepper_img(black) = 0;
saltpepper_img(white) = 255;
subplot(2, 2, 4);
imshow(saltpepper_img);
title('Grayscale image with noise', 'FontSize', 15);
Also see attached demos.
  2 件のコメント
Rooter Boy
Rooter Boy 2020 年 11 月 10 日
Sir, thank you very much.
Image Analyst
Image Analyst 2020 年 11 月 10 日
In this forum, you can thank people by clicking the Vote icon or "Accepting the answer" to give them reputation points. Thanks in advance.

サインインしてコメントする。


Image Analyst
Image Analyst 2020 年 11 月 10 日
There is a salt and pepper option for imnoise(). Just use that.
  1 件のコメント
Rooter Boy
Rooter Boy 2020 年 11 月 10 日
I want to use with if conditionals.
Mat black = saltpepper_noise < 30;
Mat white = saltpepper_noise > 225;
Mat saltpepper_img = img.clone();
saltpepper_img.setTo(255,white);
saltpepper_img.setTo(0,black);
I don't know how to adapt this for my codes.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeImage Processing Toolbox についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by