Matlab corta placas de circuito

Finalmente se hace la imagen defectuosa, solo para esta imagen (al final)
test1

%Sobel方法
I = imread('ChuanJian0.jpg');
G = rgb2gray(I);
E1 = edge(G, 'sobel');
figure, subplot(2,2,1);
imshow(I);
title('Original Color Image');
subplot(2,2,2);
imshow(E1);
title('Sobel Edge');
 
E2 = edge(G, 'roberts');
subplot(2,2,3);
imshow(E1);
title('Roberts Edge');
 
E3 = edge(G, 'log');
subplot(2,2,4);
imshow(E1);
title('LOG Edge');

% 固定阈值分割
% BW1 = im2bw(G, 220/256);
% 显示结果
% subplot(2,3,4);
% imshow(BW1);
% title('Fixed threshold');
%  
% 自动计算分割阈值
% T = graythresh(G);  
% 自动阈值分割 
% BW2 = im2bw(G, T);
% 显示分割结果
% subplot(2,3,5);
% imshow(BW2);
% title('Auto threshold');

prueba2

I = imread('ChuanJian0.jpg');
G = rgb2gray(I);
%固定阈值分割
BW1 = im2bw(G, 220/256);
%显示结果
subplot(2,1,1);
imshow(BW1);
title('Fixed threshold');
 
%自动计算分割阈值
T = graythresh(G);  
%自动阈值分割 
BW2 = im2bw(G, T);
%显示分割结果
subplot(2,1,2);
imshow(BW2);
title('Auto threshold');

prueba3

%图像分割(全局阈值,借助直方图)
clc
clear all
I=rgb2gray(imread('ChuanJian0.jpg'));
figure (1)
imhist(I);
R=I>100;%大于125的地方为白(1),小于为黑(0)
figure(2);
imshow(R);
figure(3);
% 竖值相加
G = sum(R');
plot(G);
xlabel('x');
ylabel('f(x)');
% 进行记录
J = G>mean(G);
disp(mean(G));
figure(4);
plot(J);
xlabel('x');
ylabel('J');
% 进行裁剪

2
1

%图像分割(全局阈值,借助直方图)
clc
clear all
I=rgb2gray(imread('test1.jpeg'));
figure (1);
imshow(I)
% imhist(I);
R=I>125;%大于125的地方为白(1),小于为黑(0)
% figure(2);
% imshow(R);
% 竖值相加
G = sum(R');
% figure(3);
% plot(G);
% xlabel('x');
% ylabel('f(x)');
% title('G的图像');
% 进行裁剪
% 1. 去字
chang = 600;
[m,n] = size(R);
G2 = imcrop(R,[1,1,n,chang]);
% figure(4);
% imshow(G2);
% title('G2的图像');
% 2. 现在分解,对G2进行处理
% 进行记录
G2 = sum(G2);
% figure(5);
% plot(G2);
% xlabel('x');
% ylabel('f(x)');
% title('G22的图像');
J = G2>100;
% figure(6);
% plot(J);
% xlabel('x');
% ylabel('J');
% title('J的图像');
% 计算切割点
QG = [];
j=1;
for i=1:length(J)
    if J(i)==0
        QG(j)=i;
        j = j+1;
    end
end
% figure(7);
% plot(QG);
% xlabel('x');
% ylabel('f(x)');
% title('QG的图像');
% 计算差值,计算板子的宽度
C= zeros(1,length(QG));
for i=1:length(QG)-1
    C(i) = QG(i+1)-QG(i);
end
% figure(8);
% plot(C);
% xlabel('x');
% ylabel('f(x)');
% title('C的图像');
% 所以按照这两个数进行分割
QG = (C>2).*QG;
% figure(9);
% plot(QG);
% xlabel('x');
% ylabel('f(x)');
% title('QG的图像');
% 接下来按照QG中的数字进行分割
fenGe = [];
fenGeOne = [];
a = 1;
for i=1:length(QG)
    if QG(i)>0
        fenGe(a) = QG(i);
        a = a + 1;
    end
end
fenGe
b= 1;
figure();
for i = 1:length(fenGe)-1
    fenGeOne = I(1:chang,fenGe(i):fenGe(i+1));
    subplot(3,4,b);
    imshow(fenGeOne);
    b = b+1;
    if i==length(fenGe)-1
        fenGeOne = I(1:chang,fenGe(i+1):n);
        subplot(3,4,b);
        imshow(fenGeOne);
    end
end

Experimento 3 Segmentación de imágenes

Horas experimentales: 8 horas.

(1) Propósito experimental
1. Utilice MATLAB para estudiar los principios de algoritmos comunes de segmentación de imágenes y detección de bordes;
2. Dominar el uso de las funciones de segmentación de dominios de imágenes y detección de bordes de MATLAB;
3. Comprender los algoritmos y usos de la detección de bordes y comparar las diferencias entre operadores de detección de bordes como Sobel, Prewitt y Canny;
4. Segmentar imágenes de escenas específicas.
(2) Contenido experimental y principio experimental
1. Utilice las funciones de segmentación de imágenes y detección de bordes de la caja de herramientas de imágenes de Matlab para procesar imágenes normales.
2. Las imágenes de plantas verdes se segmentaron utilizando el método del factor verde y el espacio de color HSV respectivamente;
3. Segmentar la imagen de la fruta en el espacio de color YCbCr;
4. Coloque los paneles solares y segmente cada pieza para obtener la imagen de destino del defecto.
(3) Pasos experimentales
1. Segmentación de umbral en escala de grises
(1) Imagen de segmentación de umbral global:
primero convierta una imagen en color en una imagen en escala de grises, muestre su histograma, consulte la distribución de la escala de grises en el histograma e intente determinar el umbral; el tamaño del umbral debe ajustarse repetidamente hasta que el efecto de binarización sea más satisfactorio. Repita el proceso anterior agregando ruido gaussiano de media cero a la imagen, prestando atención a la selección del umbral.
(2) Segmentación de umbral local de imágenes:
seleccione una imagen de su elección, realice una segmentación de umbrales múltiples en la imagen y preste atención a la selección de umbrales.
2. Detección de bordes
(1) Experimento de segmentación de imágenes usando el operador de Roberts, cargue y muestre una imagen *.gif o *.tif;
use el operador de Roberts para realizar el procesamiento de detección de bordes en la imagen; el operador de Roberts es un par de plantillas, correspondientes La matriz es:
rh = [0 1;-1 0];rv = [1 0;0 -1];
Aquí rh es el operador de Roberts horizontal y rv es el operador de Roberts vertical. Los resultados de detección de límites horizontales y verticales procesados ​​se pueden mostrar;
el módulo del gradiente se calcula utilizando el método de "distancia euclidiana" y se muestran los resultados de la detección; los resultados de la detección se binarizan y se muestran los resultados del procesamiento.
(2) Segmentación de imágenes utilizando el operador Prewitt, el proceso es el mismo que todos los pasos en (1).
(3) Segmentación de imágenes utilizando el operador Sobel, el proceso es el mismo que todos los pasos en (1).
(4) Utilice el operador Canny para la segmentación de imágenes. El proceso es el mismo que todos los pasos en (1).
3.Las imágenes de plantas verdes se segmentaron utilizando el método del factor verde y el espacio de color HSV respectivamente;
(1) Pasos del método del factor verde:
 Separación de canales de la imagen RGB;
 Normalizar cada canal;  Calcular
el factor súper verde;  Realizar la segmentación del umbral en la imagen en escala de grises del factor súper verde. (2) Pasos de segmentación de plantas verdes basados ​​en HSV:  Convertir imágenes RGB en imágenes HSV;  Realizar separación de canales en imágenes HSV;  Determinar el rango H de plantas verdes;  Establecer los datos fuera del rango en el componente H en 0;  Para el componente H procesado se somete a segmentación de umbral. 4.Segmentar la imagen de la fruta en el espacio de color YCbCr; 5. Coloque los paneles solares y segmente cada pieza para obtener la imagen de destino del defecto.  Coloque los cortes  Obtenga subimágenes de cada corte  Realice la segmentación de imágenes en cada subimagen de corte para obtener la imagen de destino del defecto.













(4) Requisitos del informe del experimento
1. Describir el algoritmo de procesamiento de imágenes anterior;
2. Enumere los procedimientos de procesamiento de imágenes anteriores;
3. Registrar y analizar los resultados experimentales;
4. Escribe sobre tu experiencia.

Las imágenes de plantas verdes se segmentan utilizando el método del factor verde y el espacio de color HSV respectivamente;

Diagrama de segmentación de plantas verdes.

%超绿特征分割
%先用最大类间方差法自动计算最佳阈值T,然后计算超绿分量ExG=2G-R-B,大于等于T,赋值为255,反之赋值为0
clear all;
clc;
image = imread('test2.JPG');
image = im2double(image); %图像运算不能用uint8类型,会发生溢出现象,要转成double类型
R = image(:,:,1);
G = image(:,:,2);
B = image(:,:,3);
ExG = 2*G-R-B;
[m,n] = size(ExG);
T = graythresh(ExG);%graythresh函数是使用OTSU(大津)算法返回输出最佳阈值的算法。
h = ExG;
for i = 1:m
    for j= 1:n 
        if h(i,j) >= T
            h(i,j)=255;
        else h(i,j)=0;
        end
    end
end
subplot(131),imshow(image),title('原始图片');
subplot(132),imshow(ExG),title('超绿灰度化')
subplot(133),imshow(h),title('超绿分割二值图')

Escrito por mi mismo

clc
clear all
I=imread('test2.JPG');
figure (1);
imshow(I)
%%R通道
R = I(:,:,1);
figure (2);
imshow(R);
title('R通道');
imhist(R);
%%G通道
G = I(:,:,2);
figure (3);
imshow(G);
title('G通道');
imhist(G);
%%B通道
B = I(:,:,3);
figure (4);
imshow(B);
title('B通道');
imhist(B);

Aquí está la conversión entre HSV y RGB.

clc
clear all
I=imread('test2.JPG');
figure (1);
imshow(I)
RGB = I;
HSV=rgb2hsv(RGB);%%表示将RGB图像转换为HSV图像。
figure();
imshow(HSV);
title('HSV图像');

Pasos de segmentación de plantas verdes según HSV:

Empalme:

close all;clear all;clc;
I=imread('test.jpeg');%读入图片
% figure,imshow(I);
I_h=rgb2hsv(I);%RGB转hsv
[height,width,c]=size(I);
h = I_h(:,:,1);
s = I_h(:,:,2);
v = I_h(:,:,3);
figure,
subplot(2,2,1),imshow(I_h);title('hsv格式图');
subplot(2,2,2),imshow(h);title('h');
subplot(2,2,3),imshow(s);title('s');
subplot(2,2,4),imshow(v);title('v');
% figure,
% imhist(h);
% % 得到阈值 0.5
% one = h>0;
% figure,
% imshow(one);

for i=1:height
    for j=1:width
        h=I_h(i,j,1);
        s=I_h(i,j,2);
        v=I_h(i,j,3);
%         通过将h通道颜色值特定范围内饱和度设为0,保留范围外颜色值
        if 0.38<h || h<0.15
            I_h(i,j,2)=0;
        end
    end
end
I_r=hsv2rgb(I_h);
figure, imshow(I_r);

buscando código

clear all;
clc;
flag = imread('test.jpeg'); % 读取图像       
figure;
imshow(flag); % 展示图像     
% 将图像的rgb色彩空间转化至hsv色彩空间
flag_hsv = rgb2hsv(flag);      
% 创建一个白色图像,将特定颜色提取到此处
flag_new = 255*ones(size(flag));
% 将该图像转至hsv色彩空间
flag_new_hsv = rgb2hsv(flag_new);
% 找出图像中绿色的像素
[row, col] = ind2sub(size(flag_hsv),find(flag_hsv(:,:,1)>0.12...
& flag_hsv(:,:,1)< 0.6 & flag_hsv(:,:,2)>0.16 & flag_hsv(:,:,3)>0.18));
% 将图像中的绿色像素复制到刚才新建的白色图像中
for i = 1 : length(row)
    flag_new_hsv(row(i),col(i),:) = flag_hsv(row(i),col(i),:);
end
% 将提取出来的绿色,转化至rgb空间,进行展示
flag_green = hsv2rgb(flag_new_hsv);
figure
imshow(flag_green)

4. Segmentar imágenes de frutas en el espacio de color YCbCr

000

% I = imread("test2.jpeg");
% % I = rgb2gray(I);
% YCBCR = rgb2ycbcr(RGB);
% imshow(YCBCR),title('YCBCR');

clc,clear,close all;
f=imread('test2.jpeg');
imshow(f);
fy=rgb2ycbcr(f);
cr=fy(:,:,3);
figure,imshow(cr);
% figure();imhist(cr);
cr(cr<100|cr>132)=0;
cr(cr~=0)=255;
% figure,imshow(cr);
bw=imbinarize(cr);
% figure,imshow(bw);
bw=imfill(bw,'holes');
% figure,imshow(bw);

bwao=bwareaopen(bw,500);
figure,imshow(bwao);

[r,c]=find(bwao);
resual=f(min(r):max(r),min(c):max(c),:);
figure,imshow(resual);


5. Detección de bordes

clc;clear all;
img = imread('test.png');
figure;
img = rgb2gray(img);
imshow(img),title("原图像");
[ROW,COL] = size(img);
img = double(img);
new_img = zeros(ROW,COL); %新建画布
%定义robert算子
roberts_x = [1,0;0,-1];
roberts_y = [0,-1;1,0];
for i = 1:ROW - 1
    for j = 1:COL - 1
        funBox = img(i:i+1,j:j+1);
        G_x = roberts_x .* funBox;
        G_x = abs(sum(G_x(:)));
        G_y = roberts_y .* funBox;
        G_y = abs(sum(G_y(:)));
        roberts_xy  = G_x * 0.5 + G_y * 0.5;
        new_img(i,j) = roberts_xy;
    end
end
figure(2);
imshow(new_img/255),title("robert算子的图像");
% 定义laplace算子
laplace = [0,1,0;1,-4,1;0,1,0];
for i = 1:ROW - 2
    for j = 1:COL - 2
        funBox = img(i:i+2,j:j+2);
        G = laplace .* funBox;
        G = abs(sum(G(:)));
        new_img(i+1,j+1) = G;
    end
end
figure(3)
imshow(new_img/255),title("laplace算子的图像");
%定义sobel算子
sobel_x = [-1,0,1;-2,0,2;-1,0,1];
sobel_y = [-1,-2,-1;0,0,0;1,2,1];
for i = 1:ROW - 2
    for j = 1:COL - 2
        funBox = img(i:i+2,j:j+2);
        G_x = sobel_x .* funBox;
        G_x = abs(sum(G_x(:)));
        G_y = sobel_y .* funBox;
        G_y = abs(sum(G_y(:)));
        sobelxy  = G_x * 0.5 + G_y * 0.5;
        new_img(i+1,j+1) = sobelxy;
    end
end
figure(4);
imshow(new_img/255),title("sobel的图像");
%定义Prewitt算子
sobel_x = [-1,0,1;-1,0,1;-1,0,1];
sobel_y = [-1,-1,-1;0,0,0;1,1,1];
for i = 1:ROW - 2
    for j = 1:COL - 2
        funBox = img(i:i+2,j:j+2);
        G_x = sobel_x .* funBox;
        G_x = abs(sum(G_x(:)));
        G_y = sobel_y .* funBox;
        G_y = abs(sum(G_y(:)));
        sobelxy  = G_x * 0.5 + G_y * 0.5;
        new_img(i+1,j+1) = sobelxy;
    end
end
figure(5);
imshow(new_img/255),title("Prewitt的图像");

function test(I_in)
    figure(1),subplot(121),imshow(I_in),title('原图');
    [row,col] = size(I_in);
    I=double(I_in);
    I(:, size(I_in, 2) + 1) = 195;
    I(size(I_in, 1) + 1, :) = 195;

    g = zeros(row,col);
    g_x=zeros(row,col);  % 水平方向
    g_y=zeros(row,col);  % 垂直方向

    for i=1:row
        for j=1:col
            x=abs(I(i+1,j+1)-I(i,j));
            y=abs(I(i+1,j)-I(i,j+1));
            sum=x+y;
            g(i,j) = sum;
            g_x(i,j)=x;
            g_y(i,j)=y;
        end
    end


    NumPixel = zeros(1,row);  % 建立一个256列的行向量,以统计各灰度级的像素个数
    for i = 1 : row
        for j = 1 : col
            k = g(i,j);  % k是像素点(i,j)的灰度值
            NumPixel(k+1) = NumPixel(k+1) + 1;  % 对应灰度值像素点数量加1 
        end
    end

    figure(2),bar(NumPixel);  % 灰度图像的直方图
    figure(1),subplot(122),imshow(g,[]),title('卷积结果');

    I2=g;
    for i = 1 : row
        for j = 1 : col
            if I2(i,j) < 80
                I2(i,j) = 1;
            else
                I2(i,j) = 0;
            end
        end
    end


    figure(3),subplot(121),imshow(g_x,[]),title('水平边界检测结果');
    figure(3),subplot(122),imshow(g_y,[]),title('垂直边界检测结果');
    figure,imshow(I2),title('二值化图像');
end
%图像分割(全局阈值,借助直方图)
clc
clear all
I=rgb2gray(imread('test.jpeg'));
figure (1);
imshow(I)
% imhist(I);
R=I>125;%大于125的地方为白(1),小于为黑(0)
% figure(2);
% imshow(R);
% 竖值相加
G = sum(R');
% figure(3);
% plot(G);
% xlabel('x');
% ylabel('f(x)');
% title('G的图像');
% 进行裁剪
% 1. 去字
chang = 600;
[m,n] = size(R);
G2 = imcrop(R,[1,1,n,chang]);
% figure(4);
% imshow(G2);
% title('G2的图像');
% 2. 现在分解,对G2进行处理
% 进行记录
G2 = sum(G2);
% figure(5);
% plot(G2);
% xlabel('x');
% ylabel('f(x)');
% title('G22的图像');
J = G2>100;
% figure(6);
% plot(J);
% xlabel('x');
% ylabel('J');
% title('J的图像');
% 计算切割点
QG = [];
j=1;
for i=1:length(J)
    if J(i)==0
        QG(j)=i;
        j = j+1;
    end
end
% figure(7);
% plot(QG);
% xlabel('x');
% ylabel('f(x)');
% title('QG的图像');
% 计算差值,计算板子的宽度
C= zeros(1,length(QG));
for i=1:length(QG)-1
    C(i) = QG(i+1)-QG(i);
end
% figure(8);
% plot(C);
% xlabel('x');
% ylabel('f(x)');
% title('C的图像');
% 所以按照这两个数进行分割
QG = (C>2).*QG;
% figure(9);
% plot(QG);
% xlabel('x');
% ylabel('f(x)');
% title('QG的图像');
% 接下来按照QG中的数字进行分割
fenGe = [];
fenGeOne = [];
a = 1;
for i=1:length(QG)
    if QG(i)>0
        fenGe(a) = QG(i);
        a = a + 1;
    end
end
% fenGe
b= 1;
figure();
for i = 1:length(fenGe)-1
    fenGeOne = I(1:chang,fenGe(i):fenGe(i+1));
    subplot(3,4,b);
    imshow(fenGeOne);
    b = b+1;
    if i==1
        c = fenGeOne;
    end
    if i==2
        d = fenGeOne;
    end
    if i==length(fenGe)-1
        fenGeOne = I(1:chang,fenGe(i+1):n);
        subplot(3,4,b);
        e=fenGeOne;
        imshow(fenGeOne);
    end
end
c = c(1:255,1:255);
d = d(1:255,1:255);
e = e(1:255,1:255);
figure();imshow(c);
figure();imshow(d);
figure();imshow(e);
a = corr2(c,d);
disp(a);
b = corr2(d,e);
disp(b);

Resultados finales:

%图像分割(全局阈值,借助直方图)
clc
clear all
I=rgb2gray(imread('ChuanJian0.jpg'));
figure (1);
imshow(I)
% imhist(I);
R=I>125;%大于125的地方为白(1),小于为黑(0)
% figure(2);
% imshow(R);
% 竖值相加
G = sum(R');
figure(3);
plot(G);
xlabel('x');
ylabel('f(x)');
title('G的图像');
% 进行裁剪
% 1. 去字
chang = 600;
[m,n] = size(R);
G2 = imcrop(R,[1,1,n,chang]);
% figure(4);
% imshow(G2);
% title('G2的图像');
% 2. 现在分解,对G2进行处理
% 进行记录
G2 = sum(G2);
% figure(5);
% plot(G2);
% xlabel('x');
% ylabel('f(x)');
% title('G22的图像');
J = G2>100;
% figure(6);
% plot(J);
% xlabel('x');
% ylabel('J');
% title('J的图像');
% 计算切割点
QG = [];
j=1;
for i=1:length(J)
    if J(i)==0
        QG(j)=i;
        j = j+1;
    end
end
% figure(7);
% plot(QG);
% xlabel('x');
% ylabel('f(x)');
% title('QG的图像');
% 计算差值,计算板子的宽度
C= zeros(1,length(QG));
for i=1:length(QG)-1
    C(i) = QG(i+1)-QG(i);
end
% figure(8);
% plot(C);
% xlabel('x');
% ylabel('f(x)');
% title('C的图像');
% 所以按照这两个数进行分割
QG = (C>2).*QG;
% figure(9);
% plot(QG);
% xlabel('x');
% ylabel('f(x)');
% title('QG的图像');
% 接下来按照QG中的数字进行分割
fenGe = [];
fenGeOne = [];
a = 1;
for i=1:length(QG)
    if QG(i)>0
        fenGe(a) = QG(i);
        a = a + 1;
    end
end
fenGe
b= 1;
fen = zeros([1,12]);
for i = 1:length(fenGe)-1
    fenGeOne = I(1:chang,fenGe(i):fenGe(i+1));
    subplot(3,4,b);
    imshow(fenGeOne);
    s = judge(fenGeOne);
    fen(i) = s;
    b = b+1;
    if i==length(fenGe)-1
        fenGeOne = I(1:chang,fenGe(i+1):n);
        subplot(3,4,b);
        imshow(fenGeOne);
        fen(i) = s;
    end
end
% 对缺陷图像进行显示
for i = 1:length(fenGe)
    fenGeOne = I(1:chang,fenGe(i):fenGe(i+1));
    if fen(i)==1
        figure('Name','缺陷图像');
        imshow(fenGeOne);
    end
    if i==length(fenGe)-1
        fenGeOne = I(1:chang,fenGe(i+1):n);
        if fen(i)==1
        figure('Name','缺陷图像');
        imshow(fenGeOne);
        end
    end
end
fen


% 进行判断
function s = judge(img)
%     figure();
%     subplot(1,2,1),imshow(img);
%     subplot(1,2,2),
    I = sum(img);
    I=I>109000;
%     plot(I);
    z = 0;
    for i = 1:length(I)
       if I(i)==1
           z = z+1;
       end
    end
    if z*100/length(I)>10
        s = 1;
    else s = 0;
    end
end

resultado de la operación:
1

2

3

Puntos de conocimiento:

  1. Convertir imágenes hsv y RGB
ImgHSV = rgb2hsv(ImgRGB);
ImgRGB = hsv2rgb(ImgHSV);

Supongo que te gusta

Origin blog.csdn.net/weixin_51395608/article/details/129797302
Recomendado
Clasificación