Error using edge expected input number 1 i to be two dimensional

Hello! I get the following error message: Error using edge Expected input number 1, I, to be two-dimensional. Error in edge>parse_inputs (line 476) validateattributes(I,{'numeric','logical'},{'...

Jürgen Lederer

Hello!

I get the following error message:

Error using edge Expected input number 1, I, to be two-dimensional.

Error in edge>parse_inputs (line 476)

validateattributes(I,{‘numeric’,’logical’},{‘real’,’nonsparse’,’2d’},mfilename,’I’,1);

Error in edge (line 208)

[a,method,thresh,sigma,thinning,H,kx,ky] = parse_inputs(varargin{:});

Error in V01_06042017 (line 3)

BW1 = edge(I,’sobel’);

Code:

line 476: validateattributes(I,{‘numeric’,’logical’},{‘real’,’nonsparse’,’2d’},mfilename,’I’,1);

line208: [a,method,thresh,sigma,thinning,H,kx,ky] = parse_inputs(varargin{:});

Can anyone help me? Thank you very much.


Answers (2)

Saurabh Gupta

If your image uses CMYK, you may find this post helpful for converting your data to RGB.

RGB image data can be converted to grayscale or indexed using rgb2gray or rgb2ind respectively, which can then be used in the edge function.


Image Analyst

You either have to convert the color image to gray scale,

rgbImage = imread(‘peppers.png’);

title(‘Original Color Image’)

[rows, columns, numberOfColorChannels] = size(rgbImage);

if numberOfColorChannels == 3

rgbImage = rgb2gray(rgbImage);

title(‘Gray Scale Image’)

BW1 = edge(rgbImage,‘sobel’);

title(‘Sobel Edge Image of Grayscale Image’)

title(‘Original Color Image’)

rgbImage = imread(‘peppers.png’);

[rows, columns, numberOfColorChannels] = size(rgbImage);

if numberOfColorChannels == 3

BW1 = zeros(rows, columns, numberOfColorChannels, ‘uint8’);

for k = 1 : numberOfColorChannels

thisColorChannel = rgbImage(:, :, k);

BW1(:, :, k) = uint8( 255 * edge(thisColorChannel,‘sobel’));

caption = sprintf(‘Edge image of Color Channel %d’, k);

title(‘Color Sobel Edge Image’)

end

See Also

Categories

Community Treasure Hunt

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

Start Hunting!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.

Jürgen Lederer

Hello!

I get the following error message:

Error using edge Expected input number 1, I, to be two-dimensional.

Error in edge>parse_inputs (line 476)

validateattributes(I,{‘numeric’,’logical’},{‘real’,’nonsparse’,’2d’},mfilename,’I’,1);

Error in edge (line 208)

[a,method,thresh,sigma,thinning,H,kx,ky] = parse_inputs(varargin{:});

Error in V01_06042017 (line 3)

BW1 = edge(I,’sobel’);

Code:

line 476: validateattributes(I,{‘numeric’,’logical’},{‘real’,’nonsparse’,’2d’},mfilename,’I’,1);

line208: [a,method,thresh,sigma,thinning,H,kx,ky] = parse_inputs(varargin{:});

Can anyone help me? Thank you very much.


Answers (2)

Saurabh Gupta

If your image uses CMYK, you may find this post helpful for converting your data to RGB.

RGB image data can be converted to grayscale or indexed using rgb2gray or rgb2ind respectively, which can then be used in the edge function.


Image Analyst

You either have to convert the color image to gray scale,

rgbImage = imread(‘peppers.png’);

title(‘Original Color Image’)

[rows, columns, numberOfColorChannels] = size(rgbImage);

if numberOfColorChannels == 3

rgbImage = rgb2gray(rgbImage);

title(‘Gray Scale Image’)

BW1 = edge(rgbImage,‘sobel’);

title(‘Sobel Edge Image of Grayscale Image’)

title(‘Original Color Image’)

rgbImage = imread(‘peppers.png’);

[rows, columns, numberOfColorChannels] = size(rgbImage);

if numberOfColorChannels == 3

BW1 = zeros(rows, columns, numberOfColorChannels, ‘uint8’);

for k = 1 : numberOfColorChannels

thisColorChannel = rgbImage(:, :, k);

BW1(:, :, k) = uint8( 255 * edge(thisColorChannel,‘sobel’));

caption = sprintf(‘Edge image of Color Channel %d’, k);

title(‘Color Sobel Edge Image’)

end

See Also

Categories

Community Treasure Hunt

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

Start Hunting!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.

Hello,

Throughout that example, a grayscale TIFF image is used. I would like to use a truecolor JPEG image of mine instead. Is this possible?

I was able to go through the example and create the first 6 figures, up through the 2×2 plot of the 4 different PSFs. Then I ran into problems.

The first problem I ran into was on this line:

WEIGHT = edge(I,‘sobel’,.3);

The error was: Error using edge Expected input number 1, I, to be two-dimensional.

Error in edge>parse_inputs (line 547)

validateattributes(I,{‘numeric’,‘logical’},{‘nonsparse’,‘2d’},mfilename,‘I’,1);

Error in edge (line 190)

[a,method,thresh,sigma,thinning,H,kx,ky] = parse_inputs(varargin{:});

Error in deblur_blind_deconvolution (line 55)

WEIGHT = edge(I,‘sobel’,.3);

I was able to get past that by changing the line that calls edge() to this:

WEIGHT = edge(rgb2gray(I),‘sobel’,.3);

But that gives me a different problem later on:

Error using deconvblind>parse_inputs (line 374)

If not a scalar, WEIGHT has to have size of the input image.

Error in deconvblind (line 122)

[J,P,NUMIT,DAMPAR,READOUT,WEIGHT,sizeI,classI,sizePSF,FunFcn,FunArg] =

Error in deblur_blind_deconvolution (line 63)

[J P] = deconvblind(Blurred,INITPSF,30,[],WEIGHT);

In this scenario, Blurred is a m x n x 3 matrix of uint8 values. WEIGHT is m x n matrix of double values.

I have found one way to get around this, but it is not satisfactory. After reading in the original image, I can convert it to grayscale right away, then just use that grayscale image throughout the deblur process (in the call to edge(), revert back to simply using I):

I = imread(‘mycolorjpgimage.jpg’);

figure;imshow(I);title(‘Original Image’);

I = rgb2gray(I);

But now I am stuck with a grayscale image at the end. Is there some way to convert to color and recover all of the original color data after the deblurring?

Another possibility I am thinking of is somehow converting WEIGHT from m x n to m x n x 3. But I’m stuck on how to do that.

Any help? Is deblurring a color jpeg with the WEIGHT array even possible?

(Apologies if this has been answered somewhere else already. I have googled around for hours now and have yet to find anything that addresses this specifically.)

Outrageous

1

16.04.2012, 15:00. Показов 1681. Ответов 0


Всем добрый день. В матлабе новичек, делаю задание. При медианной фильтрации выбиваются ошибки:

Matlab M
1
2
Error using medfilt2
Expected input number 1, A, to be two-dimensional.
Matlab M
1
2
Error in medfilt2>parse_inputs (line 106)
validateattributes(a, {'numeric','logical'}, {'2d','real'}, mfilename, 'A', 1);
Matlab M
1
2
Error in medfilt2 (line 48)
[a, mn, padopt] = parse_inputs(varargin{:});
Matlab M
1
2
Error in lab7 (line 18)
Fim_filt = medfilt2(Fim);

Код прграммы:

Matlab M
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
close all; clear all; clc;
reply = input('Введите имя изображения: ', 's');
   
im = imread(reply);
figure(1); 
%исходное изображение
subplot(151); 
imshow(im);
 
Fim = fft2(im);  %двумерное пр-ние Фурье
Fim(1,1) = 0;  %обнуление элемента с индексом (1,1)
Fim = abs(fftshift(Fim));  %переставление половины матрицы спектральных отключений в действительном виде
%спектр сигнала
subplot(152); 
imshow(Fim, []);
 
%медианная фильтрация
Fim_filt = medfilt2(Fim, [7,7]);
z = max(max(Fim_filt));
Fim_filt = Fim_filt ./ z;
%отфильтрованный спектр сигнала
subplot(153); 
imshow(Fim_filt);
 
Fim_filt_b = im2bw(Fim_filt, 0.3);
%бинаризация
subplot(154); 
imshow(Fim_filt_b);
 
m1 = [1 1 1; 0 0 0; -1 -1 -1];
m2 = [1 0 -1; 1 0 -1; 1 0 -1];
m3 = [1 1 0; 1 0 -1; 0 -1 -1];
m4 = [0 1 1; -1 0 1; -1 -1 0];
 
%построение контура
c1 = conv2(im2double(Fim_filt_b), im2double(m1));
c2 = conv2(im2double(Fim_filt_b), im2double(m2));
c3 = conv2(im2double(Fim_filt_b), im2double(m3));
c4 = conv2(im2double(Fim_filt_b), im2double(m4));
 
Fim_filt_c = c1 | c2 | c3 | c4;
 
%контур
subplot(155); 
imshow(Fim_filt_c);
 
figure(2); 
%3D-спектр сигнала
subplot(121); 
mesh(Fim);
%отфильтрованный 3D-спектр сигнала
subplot(122); 
mesh(Fim_filt);
 
%периметр
P = sum(sum(Fim_filt_c));
%площадь
S = sum(sum(Fim_filt_b));
 
Xs = 0;
Ys = 0;
for i=1:length(im)
    for j=1:length(im)
        if(Fim_filt_b(i,j) > 0)
            Xs = Xs + i;
            Ys = Ys + j;
        end;
    end;
end;
 
%центр тяжести
Xs=floor(Xs/S);
Ys=floor(Ys/S);
%компактность
comp=P^2/S;
 
msg1 = strcat('Периметр:', 32, num2str(P)); 
msg2 = strcat('Площадь:', 32, num2str(S));
msg3 = strcat('Центр тяжести: (', num2str(Xs), ', ', num2str(Ys), ')');
msg4 = strcat('Компактность:', 32, num2str(comp));
msgbox({msg1,msg2,msg3,msg4},'Параметры');

Картинка открывается и выводится, дальше ошибки. Подскажите, пожалуйста, в чем может быть проблема

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

Мой код показан ниже:

G= histeq(imread('F:Thesisimagesimage1.tif'));
figure,imshow(G);

Я получил следующее сообщение об ошибке, и я не уверен, почему оно появляется:

Error using histeq
Expected input number 1, I, to be two-dimensional.

Error in histeq (line 68)
validateattributes(a,{'uint8','uint16','double','int16','single'}, ...

Error in testFile1 (line 8)
G= histeq(imread('F:Thesisimagesimage1.tif'));

1 ответ

Лучший ответ

Ваше изображение, скорее всего, цветное. histeq работает только с изображениями в оттенках серого. В зависимости от того, что вы хотите сделать, вам доступны три варианта. Вы можете либо преобразовать изображение в оттенки серого, вы можете гистограмму уравнять каждый канал индивидуально, либо, что лучше воспринимать, — это преобразовать изображение в цветовое пространство HSV, гистограмму уравнять компонент V или Value, а затем преобразовать обратно в RGB. Я предпочитаю последний вариант для цветных изображений. Следовательно, одним методом будет изображение с улучшенной шкалой серого, а двумя другими — изображение с улучшенной цветностью.

Вариант №1 — преобразовать в оттенки серого, а затем выровнять

G = imread('F:Thesisimagesimage1.tif');
G = histeq(rgb2gray(G));
figure; imshow(G);

Используйте rgb2gray, чтобы преобразовать изображение в оттенки серого, затем выровняйте изображение.

Вариант №2 — Выравнивание каждого канала индивидуально

G = imread('F:Thesisimagesimage1.tif');
for i = 1 : size(G, 3)
    G(:,:,i) = histeq(G(:,:,i));
end
figure; imshow(G);

Прокрутите каждый канал и выполните выравнивание.

Вариант № 3 — преобразовать в HSV, гистограмма выровнять канал V, а затем преобразовать обратно

G = imread('F:Thesisimagesimages1.tif');
Gh = rgb2hsv(G);
Gh(:,:,3) = histeq(Gh(:,:,3));
G = im2uint8(hsv2rgb(Gh));
figure; imshow(G);

Используйте функцию rgb2hsv для преобразования цветного изображения в HSV. Затем мы используем выравнивание гистограммы на канале V или Value, а затем конвертируем обратно из HSV в RGB с помощью hsv2rgb. Обратите внимание, что на выходе hsv2rgb будет изображение типа double, поэтому, предполагая, что исходное входное изображение было uint8, используйте im2uint8 функция для преобразования из double обратно в uint8.


3

rayryeng
25 Авг 2017 в 23:26

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error ur is not detected please check the connection and reboot this software
  • Error xgen no clump guides found
  • Error windows named pipe error канал был закрыт code 109
  • Error update packages not found sync
  • Error wincc 1007001

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии