在 matlab 中的二进制图像上绘制几个 x 标记时出错

error while drawing several x-marks on a binary image in matlab

我正在尝试在二进制图像上绘制几个x标记到一些坐标。 我的输出应该是这样的

为此我在下面写了一些代码

clear all;

% Here four co-ordinates are provided as an example. In my main code the co-  ordinates will be hundred or thousands 
position{1}.x = 10;
position{1}.y = 10;
position{2}.x = 20;
position{2}.y = 20;
position{3}.x = 30;
position{3}.y = 30;
position{4}.x = 40;
position{4}.y = 40;

% Read image as binary
image = imread('test34.jpg');
figure('name','Main Image'),imshow(image);

gray_image=rgb2gray(image);
level = graythresh(gray_image);
binary_image = im2bw(image,level);

% Define color of the x-marker and initializing shapes which i want to draw
red = uint8([255 0 0]);
markerInserter = vision.MarkerInserter('Shape','X-mark','BorderColor','Custom','CustomBorderColor',red);

i = 1;
% The loop will continue to the number of co-ordinates which will never be predefined in my main code

while i<=numel(position) 
    % Converting binary to RGB for only once. 
    if i == 1
        rgb = repmat(binary_image, [1, 1, 3]);
    else

        rgb = repmat(binary_image, [1, 1, 1]);
    end       
    % Position where x-marks will be drawn

    Pts = int32([position{i}.x position{i}.y]);
    % Draw x-marks  
    binary_image = step(markerInserter, rgb, Pts);

    i = i+1;
end

figure('name','binary_image'),imshow(binary_image);

但我遇到了这些错误

Error using images.internal.imageDisplayValidateParams>validateCData (line 119)

If input is logical (binary), it must be two-dimensional.

Error in images.internal.imageDisplayValidateParams (line 27)

common_args.CData = validateCData(common_args.CData,image_type);

Error in images.internal.imageDisplayParseInputs (line 78)

common_args = images.internal.imageDisplayValidateParams(common_args);

Error in imshow (line 227)

[common_args,specific_args] = ...

Error in test2 (line 39)

figure('name','binary_image'),imshow(binary_image);

我尝试了一些示例,但它们是在 RGB 图像 上进行实验的,而 我需要在二进制图像 上进行实验,这就是我得到的地方错误。

为什么我会收到这些错误,解决方案是什么?

请提供正确代码的解释。

你的代码(对我来说)似乎有点复杂,因为它的目的。这是一个简单的示例,演示如何在二值图像上使用 scatter 绘制红色十字。如您所见,图像本身是二进制的,标记是彩色的,因此 'net' 图像不再是二进制的...此外,在应用 [=12 之前无需将 RGB 图像转换为灰度级=].

并且不要忘记使用 hold on 以避免在添加标记时丢弃图像!

这是带有注释的代码:

clear
clc
close all

%// Read image
MyImage = imread('peppers.png');

%// Convert to binary. No need to use rgb2gray.
MyBWImage = im2bw(MyImage(:,:,2));

%// Define some x- and y positions for markers
xpositions = linspace(10,300,40);
ypositions = linspace(20,500,40);

imshow(MyBWImage)

%// IMPORTANT!!
hold on

%// Draw markers
scatter(xpositions.',ypositions.',80,'r','x')

输出:

这是你的意思吗?