matlab之如何设置colormap, 以一个figure中画多幅图

本文介绍了一个实用的Matlab程序,用于解决在一个figure中绘制多幅图并设置不同colormap的问题。通过使用freezeColors和cbfreeze函数,可以实现在同一figure内展示多个独立颜色条的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

function freezeColors(varargin)
% freezeColors  Lock colors of plot, enablingmultiple colormaps per figure. (v2.3)
%
  Problem: There is only onecolormap per figure. This function provides
     an easy solution when plots using different colomaps aredesired
     in the same figure.
%
  freezeColors freezes thecolors of graphics objects in the current axis so
     that subsequent changes to the colormap (or caxis) will not changethe
     colors of these objects. freezeColors works on any graphicsobject
     with CData in indexed-color mode: surfaces, images,scattergroups,
     bargroups, patches, etc. It works by converting CData to true-colorrgb
     based on the colormap active at the time freezeColors iscalled.
%
  The original indexed colordata is saved, and can be restored using
     unfreezeColors, making the plot once again subject to the colormapand
     caxis.
%
%
  Usage:
     freezeColors       applies to all objects in current axis (gca),
     freezeColors(axh)   same, butworks on axis axh.
%
  Example:
     subplot(2,1,1); imagesc(X); colormap hot; freezeColors
     subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc...
%
     Note: colorbars must also be frozen. Due to Matlab 'improvements'this can
   nolonger be done with freezeColors. Instead, please
   usethe function CBFREEZE by Carlos Adrian Vargas Aguilera
   thatcan be downloaded from the MATLAB File Exchange
   (http://www.mathworks.com/matlabcentral/fileexchange/24371)
%
     h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar)
%
     For additional examples, see test/test_main.m
%
  Side effect on render mode:freezeColors does not work with the painters
     renderer, because Matlab doesn't support rgb color data in
     painters mode. If the current renderer is painters,freezeColors
     changes it to zbuffer. This may have unexpected effects on otheraspects
     of your plots.
%
     See also unfreezeColors, freezeColors_pub.html, cbfreeze.
%
%
  John Iversen (iversen@nsi.edu) 3/23/05
%

  Changes:
  JRI (iversen@nsi.edu)4/19/06   Correctly handlesscaled integer cdata
  JRI9/1/06   should now handle allobjects with cdata: images, surfaces,
              scatterplots. (v 2.1)
  JRI 11/11/06 Preserves NaNcolors. Hidden option (v 2.2, not uploaded)
  JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v2.3)
  JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it.
  JRI4/9/08   Fix preserving caxis forobjects within hggroups (e.g. contourf)
  JRI4/7/10   Change documentation forcolorbars

% Hidden option for NaN colors:
  Missing data are oftenrepresented by NaN in the indexed color
  data, which renderstransparently. This transparency will be preserved
  when freezing colors. Ifinstead you wish such gaps to be filled with
  a real color, add'nancolor',[r g b] to the end of the arguments. E.g.
  freezeColors('nancolor',[r gb]) or freezeColors(axh,'nancolor',[r g b]),
  where [r g b] is a colorvector. This works on images & pcolor, but noton
  surfaces.
  Thanks to Fabiano Busdraghiand Jody Klymak for the suggestions. Bugfixes
  attributed in the code.

% Free for all uses, but please retain the following:
  Original Author:
  John Iversen, 2005-10
  john_iversen@post.harvard.edu

appdatacode = 'JRI__freezeColorsData';

[h, nancolor] = checkArgs(varargin);

%gather all children with scaled or indexed CData
cdatah = getCDataHandles(h);

%current colormap
cmap = colormap;
nColors = size(cmap,1);
cax = caxis;

% convert object color indexes into colormap to true-color datausing
current colormap
for hh = cdatah',
    g =get(hh);
   
    %preserveparent axis clim
    parentAx =getParentAxes(hh);
    originalClim= get(parentAx,'clim');   
  
     Note: Special handling ofpatches: For some reason, setting
     cdata on patches created bybar() yields an error,
     so instead we'll setfacevertexcdata instead for patches.
    if~strcmp(g.Type,'patch'),
       cdata = g.CData;
    else
       cdata = g.FaceVertexCData;
    end
   
    %get cdatamapping (most objects (except scattergroup) have it)
    ifisfield(g,'CDataMapping'),
       scalemode = g.CDataMapping;
    else
       scalemode = 'scaled';
    end
   
    %saveoriginal indexed data for use with unfreezeColors
    siz =size(cdata);
   setappdata(hh, appdatacode, {cdata scalemode});

    %convertcdata to indexes into colormap
    ifstrcmp(scalemode,'scaled'),
       %4/19/06 JRI, Accommodate scaled display of integer cdata:
            in MATLAB, uint * double = uint, so must coerce cdata todouble
            Thanks to O Yamashita for pointing this need out
       idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) *nColors);
    else %directmapping
       idx = cdata;
       /8/09 in case direct data is non-int (e.g.image;freezeColors)
       % (Floor mimics how matlab converts data into colormapindex.)
       % Thanks to D Armyr for the catch
       idx = floor(idx);
    end
   
    %clamp to[1, nColors]
   idx(idx<1) = 1;
   idx(idx>nColors) = nColors;

    %handlenans in idx
    nanmask =isnan(idx);
   idx(nanmask)=1; %temporarily replace w/ a valid colormap index

    %maketrue-color data--using current colormap
    realcolor =zeros(siz);
    for i =1:3,
       c = cmap(idx,i);
       c = reshape(c,siz);
       c(nanmask) = nancolor(i); %restore Nan (or nancolor ifspecified)
       realcolor(:,:,i) = c;
    end
   
    %apply newtrue-color color data
   
    %true-coloris not supported in painters renderer, so switch out of that
    ifstrcmp(get(gcf,'renderer'), 'painters'),
       set(gcf,'renderer','zbuffer');
    end
   
    %replaceoriginal CData with true-color data
    if~strcmp(g.Type,'patch'),
       set(hh,'CData',realcolor);
    else
       set(hh,'faceVertexCData',permute(realcolor,[1 3 2]))
    end
   
    %restoreclim (so colorbar will show correct limits)
    if~isempty(parentAx),
       set(parentAx,'clim',originalClim)
    end
   
end %loop on indexed-color objects


%============================================================================%
% Local functions

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% getCDataHandles -- get handles of all descendents with indexedCData
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function hout = getCDataHandles(h)
% getCDataHandles  Find all objects with indexedCData

%recursively descend object tree, finding objects with indexedCData
% An exception: don't include children of objects that themselveshave CData:
  for example, scattergroupsare non-standard hggroups, with CData. Changing
  such a group's CDataautomatically changes the CData of its children,
  (as well as the children'shandles), so there's no need to act on them.

error(nargchk(1,1,nargin,'struct'))

hout = [];
if isempty(h),return;end

ch = get(h,'children');
for hh = ch'
    g =get(hh);
    ifisfield(g,'CData'),    %does object have CData?
       %is it indexed/scaled?
       if ~isempty(g.CData) &&isnumeric(g.CData) &&size(g.CData,3)==1,
           hout = [hout; hh]; %#ok<AGROW> %yes,add to list
       end
    else %noCData, see if object has any interesting children
           hout = [hout; getCDataHandles(hh)];%#ok<AGROW>
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% getParentAxes -- return handle of axes object to which a givenobject belongs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hAx = getParentAxes(h)
% getParentAxes  Return enclosing axes of a givenobject (could be self)

error(nargchk(1,1,nargin,'struct'))
%object itself may be an axis
if strcmp(get(h,'type'),'axes'),
    hAx =h;
    return
end

parent = get(h,'parent');
if (strcmp(get(parent,'type'), 'axes')),
    hAx =parent;
else
    hAx =getParentAxes(parent);
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% checkArgs -- Validate input arguments
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [h, nancolor] = checkArgs(args)
% checkArgs  Validate input arguments tofreezeColors

nargs = length(args);
error(nargchk(0,3,nargs,'struct'))

%grab handle from first argument if we have an odd number ofarguments
if mod(nargs,2),
    h =args{1};
    if~ishandle(h),
       error('JRI:freezeColors:checkArgs:invalidHandle',...
           'The first argument must be a valid graphics handle (to anaxis)')
    end
    % 4/2010check if object to be frozen is a colorbar
    ifstrcmp(get(h,'Tag'),'Colorbar'),
     if ~exist('cbfreeze.m'),
       warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',...
           ['You seem to be attempting to freeze a colorbar. This nolonger'...
           'works. Please read the help for freezeColors for thesolution.'])
     else
       cbfreeze(h);
       return
     end
    end
    args{1} =[];
    nargs =nargs-1;
else
    h =gca;
end

%set nancolor if that option was specified
nancolor = [nan nan nan];
if nargs == 2,
    ifstrcmpi(args{end-1},'nancolor'),
       nancolor = args{end};
       if ~all(size(nancolor)==[1 3]),
           error('JRI:freezeColors:checkArgs:badColorArgument',...
               'nancolor must be [r g b] vector');
       end
       nancolor(nancolor>1) = 1;nancolor(nancolor<0) = 0;
    else
       error('JRI:freezeColors:checkArgs:unrecognizedOption',...
           'Unrecognized option (%s). Only ''nancolor'' isvalid.',args{end-1})
    end
end

 

 

function CBH = cbfreeze(varargin)
�FREEZE   Freezes the colormap ofa colorbar.
%
  SYNTAX:
         cbfreeze
         cbfreeze('off')
         cbfreeze(H,...)
   CBH = cbfreeze(...);
%
  INPUT:
      - Handles of colorbars to be freezed, or from figures tosearch
           for them or from peer axes (see COLORBAR).
           DEFAULT: gcf (freezes all colorbars from the current figure)
   'off' - Unfreezes the colorbars, other options are:
             'on'   Freezes
             'un'    same as'off'
             'del'   Deletes thecolormap(s).
           DEFAULT: 'on' (of course)
%
  OUTPUT (all optional):
   CBH - Color bar handle(s).
%
  DESCRIPTION:
   MATLAB works with a unique COLORMAP by figure which is a big
   limitation. Function FREEZECOLORS by John Iversen allows touse
   different COLORMAPs in a single figure, but it fails freezingthe
   COLORBAR. This program handles this problem.
%
  NOTE:
   * Optional inputs use its DEFAULT value when not given or [].
   * Optional outputs may or not be called.
   * If no colorbar is found, one is created.
   * The new frozen colorbar is an axes object and does notbehaves
     as normally colorbars when resizing the peer axes. Although,some
     time the normal behavior is not that good.
   * Besides, it does not have the 'Location' property anymore.
   * But, it does acts normally: no ZOOM, no PAN, no ROTATE3D andno
     mouse selectable.
   * No need to say that CAXIS and COLORMAP must be defined beforeusing
     this function. Besides, the colorbar location. Anyway, 'off'or
     'del' may help.
   * The 'del' functionality may be used whether or not thecolorbar(s)
     is(are) froozen. The peer axes are resized back. Try:
      >> colorbar, cbfreeze del
%
  EXAMPLE:
   surf(peaks(30))
   colormap jet
   cbfreeze
   colormap gray
   title('What...?')
%
  SEE ALSO:
   COLORMAP, COLORBAR, CAXIS
   and
   FREEZECOLORS by John Iversen
   at http://www.mathworks.com/matlabcentral/fileexchange
%
%
  ---
 MFILE:   cbfreeze.m
  VERSION: 1.1 (Sep 02, 2009)(<ahref="matlab:web('http://www.mathworks.com/matlabcentral/fileexchange/authors/11258')">download</a>)
  MATLAB: 7.7.0.471 (R2008b)
  AUTHOR: Carlos Adrian Vargas Aguilera (MEXICO)
  CONTACT: nubeobscura@hotmail.com

  REVISIONS:
 1.0     Released. (Jun 08, 2009)
 1.1     Fixed BUG with image handle on MATLAB R2009a. Thanks toSergio
          Muniz. (Sep 02, 2009)

  DISCLAIMER:
  cbfreeze.m is provided "asis" without warranty of any kind, under the
  revised BSD license.

  Copyright (c) 2009 CarlosAdrian Vargas Aguilera


% INPUTS CHECK-IN
%-------------------------------------------------------------------------

% Parameters:
cbappname ='Frozen';        % Colorbar application data with fields:
                             % 'Location' from colorbar
                             % 'Position' from peer axes befor colorbar
                             %'pax'     handle from peer axes.
axappname = 'FrozenColorbar'; % Peer axes application data withfrozen
                             % colorbar handle.
 
% Set defaults:
S ='on';                  Sopt = {'on','un','off','del'};
H = get(0,'CurrentFig');

% Check inputs:
if nargin==2 &&(~isempty(varargin{1}) &&all(ishandle(varargin{1})) &&...
  isempty(varargin{2}))
 
 % Check for CallBacks functionalities:
 % ------------------------------------
 
 varargin{1} = double(varargin{1});
 
 ifstrcmp(get(varargin{1},'BeingDelete'),'on')
  % Working as DeletFcn:

  if (ishandle(get(varargin{1},'Parent'))&& ...
     ~strcmpi(get(get(varargin{1},'Parent'),'BeingDeleted'),'on'))
    % The handleinput is being deleted so do the colorbar:
    S ='del';
   
   if~isempty(getappdata(varargin{1},cbappname))
    % The frozencolorbar is being deleted:
    H =varargin{1};
   else
    % The peeraxes is being deleted:
    H =ancestor(varargin{1},{'figure','uipanel'});
   end
  
  else
   % The figure is gettingclose:
   return
  end
 
 elseif (gca==varargin{1}&& ...
                    gcf==ancestor(varargin{1},{'figure','uipanel'}))
  % Working as ButtonDownFcn:
 
  cbfreezedata =getappdata(varargin{1},cbappname);
  if ~isempty(cbfreezedata)
   ifishandle(cbfreezedata.ax)
    % Turns thepeer axes as current (ignores mouse click-over):
   set(gcf,'CurrentAxes',cbfreezedata.ax);
    return
   end
  else
   % Clears applicationdata:
  rmappdata(varargin{1},cbappname)
  end
  H = varargin{1};
 end
 
else
 
 % Checks for normal calling:
 % --------------------------
 
 % Looks for H:
 if nargin &&~isempty(varargin{1}) &&all(ishandle(varargin{1}))
  H = varargin{1};
  varargin(1) = [];
 end

 % Looks for S:
 if ~isempty(varargin)&& (isempty(varargin{1}) ||ischar(varargin{1}))
  S = varargin{1};
 end
end

% Checks S:
if isempty(S)
 S = 'on';
end
S = lower(S);
iS = strmatch(S,Sopt);
if isempty(iS)
 error('CVARGAS:cbfreeze:IncorrectStringOption',...
  ['Unrecognized ''' S ''' argument.' ])
else
 S = Sopt{iS};
end

% Looks for CBH:
CBH = cbfreeze(H); �H = cbhandle(H);

if ~strcmp(S,'del') &&isempty(CBH)
 % Creates a colorbar and peer axes:
 pax = gca;
 CBH = colorbar('peer',pax);
else
 pax = [];
end


%-------------------------------------------------------------------------
% MAIN
%-------------------------------------------------------------------------
% Note: only CBH and S are necesary, but I use pax to avoid the useof the
     "hidden" 'Axes' COLORBAR's property. Why... �

% Saves current position:
fig = get(  0,'CurrentFigure');
cax = get(fig,'CurrentAxes');

% Works on every colorbar:
for icb = 1:length(CBH)
 
 % Colorbar axes handle:
  = double(CBH(icb));
 
 % This application data:
 cbfreezedata = getappdata(h,cbappname);
 
 % Gets peer axes:
 if ~isempty(cbfreezedata)
  pax = cbfreezedata.pax;
  if ~ishandle(pax) % just in case
   rmappdata(h,cbappname)
   continue
  end
 elseif isempty(pax) % not generated
  try
   pax =double(get(h,'Axes'));  % NEW feature inCOLORBARs
  catch
   continue
  end
 end
 
 % Choose functionality:
 switch S
 
  case 'del'
   % Deletes:
   if~isempty(cbfreezedata)
    % Returnsaxes to previous size:
    oldunits =get(pax,'Units');
   set(pax,'Units','Normalized');
   set(pax,'Position',cbfreezedata.Position)
   set(pax,'Units',oldunits)
   set(pax,'DeleteFcn','')
    ifisappdata(pax,axappname)
    rmappdata(pax,axappname)
    end
   end
   ifstrcmp(get(h,'BeingDelete'),'off')
   delete(h)
   end
  
  case {'un','off'}
   % Unfrozes:
   if~isempty(cbfreezedata)
   delete(h);
   set(pax,'DeleteFcn','')
    ifisappdata(pax,axappname)
    rmappdata(pax,axappname)
    end
    oldunits =get(pax,'Units');
   set(pax,'Units','Normalized')
   set(pax,'Position',cbfreezedata.Position)
   set(pax,'Units',oldunits)
    CBH(icb) =colorbar(...
    'peer'   ,pax,...
    'Location',cbfreezedata.Location);
   end
 
  otherwise % 'on'
   % Freezes:
 
   % Gets colorbar axesproperties:
   cb_prop  =get(h);
  
   % Gets colorbar image handle.Fixed BUG, Sep 2009
   hi =findobj(h,'Type','image');
   
   % Gets image data andtransform it in a RGB:
   CData = get(hi,'CData');
   if size(CData,3)~=1
    % It'salready frozen:
   continue
   end
 
   % Gets image tag:
   Tag = get(hi,'Tag');
 
   % Deletes previous colorbarpreserving peer axes position:
   oldunits =get(pax,'Units');
             set(pax,'Units','Normalized')
   Position =get(pax,'Position');
   delete(h)
   cbfreezedata.Position =get(pax,'Position');
             set(pax,'Position',Position)
             set(pax,'Units',oldunits)
 
   % Generates new colorbaraxes:
   % NOTE: this is needed becauseeach time COLORMAP or CAXIS is used,
       MATLAB generates a new COLORBAR! This eliminates thatbehaviour
       and is the central point on this function.
   h = axes(...
   'Parent'  ,cb_prop.Parent,...
   'Units'   ,'Normalized',...
   'Position',cb_prop.Position...
   );
 
   % Save location for futurecall:
   cbfreezedata.Location =cb_prop.Location;
 
   % Move ticks because IMAGEdraws centered pixels:
   XLim = cb_prop.XLim;
   YLim = cb_prop.YLim;
  if    isempty(cb_prop.XTick)
    %Vertical:
    X = XLim(1)+ diff(XLim)/2;
    Y =YLim    +diff(YLim)/(2*length(CData))*[+1 -1];
   else % isempty(YTick)
    %Horizontal:
    Y = YLim(1)+ diff(YLim)/2;
    X =XLim    +diff(XLim)/(2*length(CData))*[+1 -1];
   end
 
   % Draws a new RGB image:
  image(X,Y,ind2rgb(CData,colormap),...
   'Parent'           ,h,...
   'HitTest'          ,'off',...
   'Interruptible'    ,'off',...
   'SelectionHighlight','off',...
   'Tag'              ,Tag...
  

   % Removesall  '...Mode'   properties:
   cb_fields =fieldnames(cb_prop);
  indmode   =strfind(cb_fields,'Mode');
   for k=1:length(indmode)
    if~isempty(indmode{k})
    cb_prop = rmfield(cb_prop,cb_fields{k});
    end
   end
  
   % Removes special COLORBARsproperties:
   cb_prop =rmfield(cb_prop,{...
   'CurrentPoint','TightInset','BeingDeleted','Type',...      % read-only
   'Title','XLabel','YLabel','ZLabel','Parent','Children',... % handles
   'UIContextMenu','Location',...                             % colorbars
   'ButtonDownFcn','DeleteFcn',...                            % callbacks
   'CameraPosition','CameraTarget','CameraUpVector','CameraViewAngle',...
   'PlotBoxAspectRatio','DataAspectRatio','Position',...
   'XLim','YLim','ZLim'});
  
   % And now, set new axesproperties almost equal to the unfrozen
   % colorbar:
   set(h,cb_prop)

   % CallBack features:
   set(h,...
   'ActivePositionProperty','position',...
   'ButtonDownFcn'        ,@cbfreeze,...  % mhh...
   'DeleteFcn'            ,@cbfreeze)    % again
  set(pax,'DeleteFcn'     ,@cbfreeze)    % and again! 
 
   % Do not zoom or pan orrotate:
  setAllowAxesZoom (zoom   ,h,false)
  setAllowAxesPan  (pan    ,h,false)
  setAllowAxesRotate(rotate3d,h,false)
  
   % Updates data:
   CBH(icb) =h;  

   % Saves data for futureundo:
  cbfreezedata.pax      = pax;
   setappdata( h,cbappname,cbfreezedata);
  setappdata(pax,axappname,h);
  
 end % switchfunctionality  

end  % MAIN loop


% OUTPUTS CHECK-OUT
%-------------------------------------------------------------------------

% Output?:
if ~nargout
 clear CBH
else
 CBH(~ishandle(CBH)) = [];
end

% Returns current axes:
if ishandle(cax)
 set(fig,'CurrentAxes',cax)
end


% [EOF]   cbfreeze.m
大家只要把这个.m文件matlab工作文件夹中即可,此函数用来在一个figure上作出多个立体图形。

e.g.

subplot(1,2,1)
sphere(10)
colorbar
freezeColors
subplot(1,2,2)
peaks(20)
colorbar
cbfreeze

图形如下:


[转载]给大家一个非常好用的matlab程序(一个figure中画多幅图,colo


这样在同一个figure中就显示出两个colorbar。

()
### 在 MATLAB 中生成或创建灰度像的方法 在 MATLAB 中,可以通过多种方式生成或创建灰度像。这些方法涵盖了从简单的内置函数调用到复杂的自定义算法设计。以下是几种常见的实现方式。 --- #### 方法一:使用 `rgb2gray` 将彩色像转换为灰度MATLAB 提供了一个便捷的函数 `rgb2gray`,可以直接将彩色像(RGB 像)转换为灰度像。这是最常用也是最简便的方式之一。 ```matlab % 读取一张彩色像 RGB = imread('example_image.jpg'); % 使用 rgb2gray 函数将彩色像转换为灰度像 GrayImage = rgb2gray(RGB); % 显示灰度像 imshow(GrayImage); ``` 该方法适用于已经存在的彩色像文件,并能快速生成对应的灰度版本[^2]。 --- #### 方法二:手动计算灰度值 除了依赖于现成的函数外,还可以通过编程手动计算每个像素点的灰度值。通常情况下,灰度值由红、绿、蓝三个通道按照一定权重加权求和得出。例如: \[ \text{Gray} = 0.299R + 0.587G + 0.114B \] 这种公式反映了人类视觉系统对不同颜色敏感程度的不同。 ```matlab % 加载一幅 RGB 彩色像 RGB = imread('example_image.jpg'); % 手动计算灰度值 RedChannel = double(RGB(:, :, 1)); GreenChannel = double(RGB(:, :, 2)); BlueChannel = double(RGB(:, :, 3)); GrayImageManual = uint8(0.299 * RedChannel + 0.587 * GreenChannel + 0.114 * BlueChannel); % 展示结果 figure; subplot(1, 2, 1), imshow(RGB), title('Original Color Image'); subplot(1, 2, 2), imshow(GrayImageManual), title('Grayscale Image (Manual)'); ``` 这种方式不仅加深了对色彩空间的理解,还允许用户根据需求调整各颜色分量的比例[^4]。 --- #### 方法三:直接构建纯灰色级矩阵 如果目标并非是从现有片出发而是要完全新建一个特定模式或者随机分布的灰阶,则可以直接初始化数值数组作为基础素材再赋予其形属性即可形成最终产物。 ```matlab % 创建一个 256x256 大小的渐变灰度像 [x, y] = meshgrid(linspace(0, 1, 256)); GrayGradient = uint8(x .* 255); % 或者生成固定亮度级别的单色块面 UniformGrayLevel = ones(100, 100) * 128; % 设置所有像素均为中间色调即半亮状态 % 可视化这两个例子 figure; subplot(1, 2, 1), imagesc(GrayGradient), colormap(gray), axis equal off, title('Gray Gradient'); subplot(1, 2, 2), imagesc(UniformGrayLevel), colormap(gray), axis equal off, title('Uniform Gray Level'); ``` 这段脚本展示了如何不依靠外部资源仅靠内部逻辑就能生产出具有规律变化特征或者是恒定表现形式的面内容[^1]。 --- #### 方法四:批量化处理多张彩照转黑白片 针对含有大量待加工素材的情况比如整个目录下的所有jpg格式文档等场景下,可以编写循环结构配合前面提到的技术要点逐一完成任务自动化流程简化操作步骤提升工作效率减少重复劳动强度增加灵活性适应更多复杂条件约束条件下依旧保持良好性能输出稳定可靠的结果集满足各种应用场景的要求特点如下所示: ```matlab folderPath = 'C:\path_to_images'; filePattern = fullfile(folderPath, '*.jpg'); files = dir(filePattern); for k = 1:length(files) baseFileName = files(k).name; fullFileName = fullfile(folderPath, baseFileName); fprintf('Now reading %s\n', fullFileName); originalImage = imread(fullFileName); grayscaleImage = rgb2gray(originalImage); outputFolder = 'C:\output_grayscale'; if ~exist(outputFolder, 'dir') mkdir(outputFolder); end newBaseFileName = ['gray_' baseFileName]; imwrite(grayscaleImage, fullfile(outputFolder, newBaseFileName)); end ``` 上述代码片段实现了自动查找指定路径内符合条件的所有JPEG格式影像资料并将它们一一转变为相应的灰度副本存放到另一预设好的位置等待后续进一步分析研究等工作环节继续推进下去直至达成预期目标为止[^3]. --- ### 结论 综上所述,在 MATLAB 环境里制作灰度像既可通过调用官方提供的专用接口如`rgb2gray()`迅速搞定常规事务;也能凭借自己动手编码精确控制每一个细节部分从而获得更加个性化的定制服务体验;甚至还能独立构思全新概念作品展现非凡创意才华无限可能尽在此间探索发现乐趣无穷! ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值