Tip: 칼라 영상 흑백 영상
• g = rgb2gray(f);
cafe.daum.net/RobotVision 1
dipum2 dipum2
CH 2 CH 2
IntensityTransformations
IntensityTransformations & &
SpatialFiltering SpatialFiltering
2 cafe.daum.net/RobotVision
개요
• 공간 도메인 처리의 두 가지 주요 부류에
초점:
1. 밝기
(or그레이-레벨
)변환
2. 공간 필터링
:이웃 처리
(or공간 컨볼루션
)• 위의 두 부류의 대표적인 처리 기법들을 개발
• 이 장의 대부분의 예제들
영상 enhancement
3 cafe.daum.net/RobotVision
• 공간 도메인 기법은 영상의
화소들에 직접 작용
• 공간 도메인 처리
:g(x, y) = T [ f(x, y) ]
–
f(x, y):
入力 영상 –g(x, y):
出力 영상–
T:
점 (x, y
) 주위의이웃
(그림 2.1)에 대해 정의되는 연산자• 複數 영상에 대한 연산 가능 – 예: 노이즈 경감을 위해 K 개
의 영상을 더하는 것
1 배경 1 배경
4 cafe.daum.net/RobotVision
이웃 이웃
• 어떤 점 (x,y)의
공간적 이웃
(그림 2.1 )= (x,y)를 중심으로 하는 주로 정사각형 영역
• (공간) 이웃 처리:
i) 이웃의
중심
을 영상의 좌측 위 모서리에 놓고, ii) 연산:g
(x
,y
)=
T[f
(x
,y
)] (어떤 연산? 그림 )– 이웃 화소들 을 (x, y)에서의 g 값의 계산에 사용
iii) 이웃의 중심
을 한 화소이동
하고 goto ‘step ii’.– 이동할 때마다 이웃 달라짐
그림 2.1 (x, y)의 3 3 이웃 그림 2.1 (x, y)의 3 3 이웃
1
1 1
1
) ,
( ) , ( )]
, ( [ )
, (
i j
j y
i x
f j i w y
x f T y
x g
) 1 , 1 ( )
0 , 1 ( )
1 , 1 (
) 1 , 0 ( )
0 , 0 ( )
1 , 0 (
) 1 , 1 ( )
0 , 1 ( )
1 , 1 (
w w
w
w w
w
w w
w W
6 cafe.daum.net/RobotVision
7 cafe.daum.net/RobotVision
8 cafe.daum.net/RobotVision
• 이 장의 나머지에서는 앞의
(공간 도메인 처리)식 을 다양하게 구현
– 개념 ~ 간단
– 주의:
MATLAB에 의해 구현 時데이타 클래스 와 값의 범위
에 주의.9 cafe.daum.net/RobotVision
• 가장 간단한 형태의
T:
그림 2.1의 이웃의 크기 가 1 1(단일 화소
)일 때(즉, W = w (= w(0,0)~ scalar)). 이 경우,
① g(x, y) = T[f(x,y)] = w f(x,y)
② 즉, T =
밝기 or 그레이 레벨 변환 함수
그 점에서의
f의 밝기에만 의존
• 밝기 변환 함수가 밝기 값에만 종속 (좌표(x, y) 와 無關)
g(x, y) = T[f(x,y)] g = T[ f ]
s = T(r)– r, s: 각각 f와 g의 해당 점(x, y)에서의
밝기 2 Intensity Transformation Functions 2 Intensity Transformation Functions
10 cafe.daum.net/RobotVision
• 그레이 영상의 밝기 변환을 위한 기본적인 IPT 툴:
g = imadjust(f, [low_in high_in],
[low_out high_out], gamma)
• [low_in, high_in] [low_out, high_out]
• clipping: (그림 3.2)
2.2.1 imadjust & stretchlim
2.2.1 imadjust & stretchlim
Photoshop:
Image > Adjustment > Curves…
1. 입력 영상 클래스: uint8, uint16, int16, single, double
출력 영상 클래스 = 입력 영상 클래스
2. 2nd & 3rd 인자 ~ [0, 1] (f의 클래스와 무관) – If f ~ uint8, * 255
If f ~ uint16, * 65535
– If [
low_in high_in], [
low_out high_out] ~ 빈 매트릭스([ ]), 디폴트 = [0 1]
• Q: What if high_out < low_out?
(imadjust) (imadjust)
13 cafe.daum.net/RobotVision
또는, via 메뉴: Image > Adjustment > Invert
네거티브
PhotoShop
3. gamma: 곡선의 모양을 규정
– If gamma < 1 (그림 2.2(a)), 출력 밝기 (Why?)
If gamma > 1, 출력 밝기
만일 생략하면, gamma = 1 (선형 매핑).
(함수 imadjust) (함수 imadjust)
15 cafe.daum.net/RobotVision
• 그림 2.3(a): 작은 종양이 보이는 매모그램 영상(f)
• 그림 2.3(b): 네거티브 영상
>> g1 = imadjust(f, [0 1], [1 0]);
∵ 특히
넓고 어두운 영역 속의 백색 또는 회색 디 테일을 보는 것 보다 그
反對로 보는 것이 편리 그림 2.3(b)에서의 가슴 조직 분석이 훨씬 더 쉬 워짐.
• Alternative:
g = imcomplement(f)
IPT
예제 2.1 함수 imadjust 사용하기 예제 2.1 함수 imadjust 사용하기
16 cafe.daum.net/RobotVision
17 cafe.daum.net/RobotVision
• 그림 2.3(c):
>> g2 = imadjust(f, [0.5 0.75], [0 1]);
– [0.5, 0.75] [0, 1]
로 확장 (나머지 입력 범위는?) 관심 대상 밝기 범위를 강조
• 그림 2.3(d):
>> g3 = imadjust(f, [ ], [ ], 2);
– 그레이 스케일의 아래 끝은
압축
; 위 끝은확 장
(그림 2.2(c))– Vs. 그림 2.3(c): 회색 톤 증가
(함수 imadjust) (함수 imadjust)
18 cafe.daum.net/RobotVision
그림 (c) vs. (d)
19 cafe.daum.net/RobotVision
histograms
stretchlim
Low_High = stretchlim(f)
• By default, values in Low_High specify the intensity levels that saturate the bottom and top 1% of all pixel values in f.
• >> g = imadjust(f, stretchlim(f), [ ]);
• >> g = imadjust(f, stretchlim(f), [1 0]);
21 cafe.daum.net/RobotVision
• Low_High = stretchlim(f, tol)
– tol = [low_frac high_frac]
• If tol ~ scalar ,
low_frac = tol
high_frac = 1 − low_frac
• If you omit it from the argument,
tol = [0.01 0.99] saturation level = 2%.
• If tol = 0 Low_High = [min(f(:)) max(f(:))]
22 cafe.daum.net/RobotVision
• 로그 변환 함수:
g = c*log(1 + double(f)) (c: 상수) ()
• Vs. gamma 곡선:
1. gamma < 1인 곡선(그림 2.2(a))에서 밑의 값을 0, 위의 값을 1로 설정한 것과 비슷.
2. gamma 곡선의 모양 ~ 가변적, 로그 함수의 모양 ~ 고정.
2.2 로그 및 콘트라스트-스트레칭 변환 2.2 로그 및 콘트라스트-스트레칭 변환
23 cafe.daum.net/RobotVision
24 cafe.daum.net/RobotVision
• 주요 용도: 동적 범위 축소
• 예: 푸리에 스펙트럼(CH 3)
(로그 변환 함수) (로그 변환 함수)
25 cafe.daum.net/RobotVision
>> g = c*log(1 + double(f)) 後,
>> gs = im2uint8(mat2gray(g));
– mat2gray [0, 1] im2uint8 [0, 255]
26 cafe.daum.net/RobotVision
• 그림 2.4(a):
콘트라스트- 스트레칭
변환함수∵ (1) For r < m, 출력 영상에서 좁은 범위의 더 어두운 레벨에 압축;
(2) For r > m, 좁은 범위의 더 밝은 레벨에 압축
분포를 양 극 으로 벌림 (
dynamic range )• 그림 2.4(b): 극단적 경우; 출력 ~
이진 영상
= thresholding
함수
– 영상
분할에 사용 (cf. CH 10)
27 cafe.daum.net/RobotVision
28 cafe.daum.net/RobotVision
그림 2.4(a)의 함수 그림 2.4(a)의 함수
• 그림 2.4(a)의 함수: s = T(r) =
• r, s: 각각 입력 영상, 출력 영상에서의 밝기 (@ 한 화소)
• E: 기울기 조절 (= 20 in 그림 2.4(a))
– If E ~ very large, … ? (그려 볼 것.)
• 전체 영상에 대한 공식:
g = 1../(1 + (m../(double(f ) + eps))..^E)
r E
m/ ) ( 1
1
r
Em / ) (
1
1
29 cafe.daum.net/RobotVision
• eps ?
• T(r)의 한계 값(최대) = 1
출력 값 ~ [0, 1]로 스케일링
30 cafe.daum.net/RobotVision
예제 2.2: 동적 범위 축소 위해 로그 변환 사용하기
예제 2.2: 동적 범위 축소 위해 로그 변환 사용하기
• 그림 2.5(a): [0, 1.5
10
6]의 푸리에 스펙트럼– 즉, 1.5 10
6 255; 1.5 10
3 → 0.255 0• 그림 2.5(b):
>> g = im2uint8(mat2gray(log(1 + double(f))));
>> imshow(g)
– Vs. 오리지널 영상: 개선 분명
어두운 영역의 변화는 강조; 밝 은 영역의 변화 는 억제.
31 cafe.daum.net/RobotVision
! 비교:
>> imshow(mat2gray(log(1 + double(f))));
g = im2uint8(mat2gray(log(1 + double(f))));
• HW: (HW 2.2.2)
34 cafe.daum.net/RobotVision
2.2.3 Specifying Arbitrary Intensity Transformations
• g = interp1(z, T, f)
35 cafe.daum.net/RobotVision
2.2.4 밝기 변환을 위한 유틸리티 M-함수 2.2.4 밝기 변환을 위한 유틸리티 M-함수
• In this section, 앞의 두 절에서 소개된 밝 기 변환의 다양한 측면을 統合하는 두 개 의 M-함수를 개발
36 cafe.daum.net/RobotVision
• 함수
nargin: (함수의 本文에서
) n = nargin– M-함수에 입력되는 인자의 실제 갯수 반환
함수 nargout: (출력 인자 수) n = nargout
• 예:
>> T = testhv(4, 5); % a hypothetical M-function
– 함수 本文에서, nargin은 2를, nargout은 1을 반환.
가변적인 입력 및 출력 개수 다루기 가변적인 입력 및 출력 개수 다루기
37 cafe.daum.net/RobotVision
• 옳은 수의 인자가 넘겨졌는지 확인 (함수 본문 내에서) msg = nargchk(low, high, number) % number ← nargin
• If number < low, “Not enough input parameter”
> high, “Too many input parameters” 반환 in between, then 빈 매트릭스를 반환.
• 사용 예: error(nargchk(2, 3, nargin));
함수 nargchk 함수 nargchk
38 cafe.daum.net/RobotVision
function G = testhv2(x, y, z) ...
error(nargchk(2, 3, nargin));
...
• 예:
>> testhv2(6);
Not enough input arguments.
• then 실행 중단.
보기 보기
39 cafe.daum.net/RobotVision
• 변수 varargin과 varargout
• 예:
function [m, n] = testhv3(varargin)
입력 인자 수 ~ 可變的
function [varargout] = testhv4(m, n, p)
출력 인자 수 ~ 가변적
• 입력과 출력 인자 수가 모두 가변적인 함 수도 가능.
변수 varargin과 varargout 변수 varargin과 varargout
40 cafe.daum.net/RobotVision
고정
고정 인자와 인자와 가변 가변 인자가 인자가 혼재하는 혼재하는 경우 경우
• 예: If testhv5가
① 고정 입력 인자
= 1개(x), and② 가변적 입력 인자 를 갖는다면,
function [m, n] = testhv5(x, varargin)
두 번째 입력 인자부터 varargin이 시작.
41 cafe.daum.net/RobotVision
• varargin ~
쎌 배열 혼합된 입력 집합 포함 가능
• 예:
>> [m, n] = testhv5(f, [0 0.5 1.5], A, ‘label’);
– (1) 영상; (2) 길이 3의 행 벡터; (3) 매트릭스; (4) 문자열
• 다양한 입력을 필요로 하는
함수의 구조를 단순화!!
How is it possible? Ans) cell array
42 cafe.daum.net/RobotVision
밝기
밝기 변환을 변환을 위한 위한 M M--함수 함수 2 2
• In this section, 다음 변환 함수들을 계산 하는 함수 개발 : negative, log, gamma, contrast-stretching.
• + 이 함수 작성에 함수 tofloat 사용:
[g, revertclass] = tofloat(f)
–
注: 문서화가 안된IPT 유틸리티 함수. 그 코드는 부록
C에.– logical, uint8, uint16, int16 single – revertclass:
function handle• to covert the output back to the same class as f
43 cafe.daum.net/RobotVision
• 함수 intrans에서 코드의 도움말 섹션에서
1. 함수 옵션들이 어떻게 포맷되고,
2. 가변 개수 입력들이 어떻게 다뤄지고, 3. 에러 확인이 코드에 어떻게 삽입되며,
4. 지정된 클래스에 출력 영상의 클래스가 어떻게 맞춰 지는지
를 주목.
• Remember: varargin ~ 쎌 배열 요소 선택 時
중괄호
사용!함수 intrans
(intensity transformation) 함수 intrans
(intensity transformation)
44 cafe.daum.net/RobotVision
function g = intrans(f, method, varargin)
%INTRANS Performs intensity (gray-level) transformations.
% G = INTRANS(F, ‘neg’) computes the negative of input image F.
%
% G = INTRANS(F, ‘log’, C, CLASS) computes C * log(1 + F). If the last two parameters are omitted, C defaults to 1. Because the log is used
% frequently to display Fourier spectra, parameter CLASS offers the
% option to specify the class of the output as ‘uint8’ or
% ‘uint16’. If parameter CLASS is omitted, the output is of the
% same class as the input.
%
45 cafe.daum.net/RobotVision
g = c*log(1 + double(f))
% G = INTRANS(F, ‘gamma’, GAM) …
%
% G = INTRANS(F, ‘stretch’, M, E) computes a contrast-stretching
% trasformation using …
% (default values: …)
% G = INTRANS(F, 'specified', TXFUN) performs the intensity
% transformation s = TXFUN(r) where r are input intensities, s are
% output intensities, and TXFUN is an intensity transformation
% (mapping) function, expressed as a vector with values in the
% range [0, 1]. TXFUN must have at least two values.
% For the …
r E
m / ) (
1
1
46 cafe.daum.net/RobotVision
% Verify the correct number of inputs.
error(nargchk(2, 4, nargin)) % nargchk message
if strcmp(method, 'log')
% The log transform handles image classes differently than the
% other transforms, so let the logTransform function handle that
% and then return.
g = logTransform(f, varargin{:});
return;
end
47 cafe.daum.net/RobotVision
% If f is floating point, check to see if it is in the range [0 1].
% If it is not, force it to be using function mat2gray.
if isfloat(f) && (max(f(:)) > 1 || min(f(:)) < 0) f = mat2gray(f);
end
[f, revertclass] = tofloat(f); %Store class of f for use later.
% Perform the intensity transformation specified.
48 cafe.daum.net/RobotVision
switch method case ‘neg’
g = imcomplement(f);
case 'gamma'
g = gammaTransform(f, varargin{:});
case 'stretch'
g = stretchTransform(f, varargin{:});
case 'specified'
g = spcfiedTransform(f, varargin{:});
otherwise
error('Unknown enhancement method.') End
% Convert to the class of the input image.
g = revertclass(g);
• switch-case 예:
switch (rem(n,4)==0) + (rem(n,2)==0) case0
M = odd_magic(n) case 1
M = single_even_magic(n) case 2
M = double_even_magic(n) otherwise
error('This is impossible') end
49 cafe.daum.net/RobotVision
%---%
function g = gammaTransform(f, gamma) g = imadjust(f, [ ], [ ], gamma);
%---%
function g = stretchTransform(f, varargin) if isempty(varargin)
% Use defaults.
m = mean2(f);
E = 4.0;
elseif length(varargin) == 2 m = varargin{1};
E = varargin{2};
else
error('Incorrect number of inputs for the stretch method.') end
g = 1./(1 + (m./f).^E);
cafe.daum.net/RobotVision 50
%---%
function g = spcfiedTransform(f, txfun)
% f is floating point with values in the range [0 1].
txfun = txfun(:); % Force it to be a column vector. if any(txfun) > 1 || any(txfun) <= 0
error('All elements of txfun must be in the range [0 1].') end
T = txfun;
X = linspace(0, 1, numel(T))';
g = interp1(X, T, f);
cafe.daum.net/RobotVision 51
%---%
function g = logTransform(f, varargin) [f, revertclass] = tofloat(f);
if numel(varargin) >= 2
if strcmp(varargin{2}, 'uint8') revertclass = @im2uint8;
elseif strcmp(varargin{2}, 'uint16') revertclass = @im2uint16;
else
error('Unsupported CLASS option for ''log'' method.') end
end
if numel(varargin) < 1
% Set default for C.
C = 1;
else
C = varargin{1};
end
g = C * (log(1 + f));
g = revertclass(g); cafe.daum.net/RobotVision 52
Tip: imadjust
J = imadjust(I,[low_in; high_in],[low_out; high_out],gamma)
• gamma < 1 the mapping is weighted toward higher (brighter) output values.
• gamma > 1 the mapping is weighted toward lower (darker) output values.
• gamma == 1 linear mapping
– If you omit the argument, gamma defaults to 1.
• If high_out < low_out, the output image is reversed, as in a photographic negative.
53 cafe.daum.net/RobotVision
Tip: mean2
• Compute the mean of the elements of a matrix
cafe.daum.net/RobotVision 54
• 그림 2.6(a) 콘트라스트-스트레칭 그림 2.6(b)
>> g = intrans(f, 'stretch', mean2(tofloat(f)), 0.9);
– Q1: Why apply tofloat? Ans)
– Q2: Why not use mean2(mat2gray(tofloat(f)))? Ans)
>> figure, imshow(g)
• 영상 f tofloat [0., 1.]로 스케일링 (E 값(0.9)은 대화식으로 결정되었음.)
예제 2.3 함수 intrans 사용 하기 예제 2.3 함수 intrans 사용 하기
55 cafe.daum.net/RobotVision
h1
슬라이드 55
h1 took 1 hour for the rest 11 pages (예제 3.3) --> around 5 min. per page
y, 2005-04-15
56 cafe.daum.net/RobotVision
Week 4 HW (1) Week 4 HW (1)
• intrans 이용
• 모든 method를 사용
• 각 method의 효과 확인(‘neg’ 외에는 개선 효과 보여줄 것)
• 각 method 별로 다른 영상 사용 허용(즉, 각 method에 적합한 영상을 사용해도 됨.)
cafe.daum.net/RobotVision 57
histograms
(a) imhist(f)
(b) imhist(im2double(f)) (c) intrans(f, ‘stretch’,
mean2(tofloat(f)), 0.9)
* mean2(…) 0.0672
• g = 255.* 1./(1 + (m./(f + eps)).^E);
where m = 0.0672
f = 0: (1/256) : 1 E = 0.9
>> g = 255.* 1./(1 + (0.0672./(f + eps)).^0.9);
stretchTransform
E = 0.9
(m = 0.6114)
>> x = 0:1/256:1;
>> figure, plot(x,1./(1+(m./(x + eps)).^E)); % m=.6114, E=.9
>> ylim([0 1])
S字?
62 cafe.daum.net/RobotVision
%%
f = tofloat(gray_im);
% f = im2double(f);
if ndims(f) > 2 f = rgb2gray(f) end
subplot(2,2,1); imshow(f) subplot(2,2,3); imhist(f) m = mean2(f);
E = 4.9;
g = 1./(1 + (m./(f + eps)).^E);
subplot(2,2,2); imshow(g) subplot(2,2,4); imhist(g)
M-file로 optimum E 값 찾기
Cell > Evaluate Current Cell
E = 4.9
64 cafe.daum.net/RobotVision
>> figure, plot(x,1./(1+(m./(x + eps)).^E));
65 cafe.daum.net/RobotVision
E = 4.9
g = 255.* 1./(1 + (m./(f + eps)).^E);
66 cafe.daum.net/RobotVision
An M-Function for Intensity Scaling
• g = gscale(f, method , low, high)
– 지정된 범위로 매핑(리스팅은 부록 C에) – method:
① 'full8' (the default), which scales the output to the full range [0, 255],
② 'full16', which scales the output to the full range [0, 65535].
(If included, parameters low and high are ignored in these two conversions)
③ 'minmax', in which case parameters low and high, both in the range [0, 1], must be provided.
– 입력 class == 출력 class
cafe.daum.net/RobotVision 67