Minggu, 16 Februari 2020

ANt Collony Algorithm

REFRENSI ANT:

XY =

    82    66
    91     3
    12    85
    92    94
    63    68
     9    76
    28    75
    55    39
    96    66
    97    17
    15    71
    98     3
    96    27
    49     4
    80     9
    14    83
    42    70
    92    32
    80    95
    96     3



Sistem akan auto move mencari jarak terdekat untuk melalui semua titik yang ada..



dan ini adalah grafik kecerdasannya...
Iteration 1: Best Cost = 650.2307
Iteration 2: Best Cost = 540.892
Iteration 3: Best Cost = 531.4992
Iteration 4: Best Cost = 483.6564
Iteration 5: Best Cost = 483.6564
Iteration 6: Best Cost = 483.6564
Iteration 7: Best Cost = 483.6564
Iteration 8: Best Cost = 451.971
Iteration 9: Best Cost = 451.9041
Iteration 10: Best Cost = 439.1259
Iteration 11: Best Cost = 439.1259
Iteration 12: Best Cost = 424.478
Iteration 13: Best Cost = 424.478
Iteration 14: Best Cost = 410.1005
Iteration 15: Best Cost = 410.1005
Iteration 16: Best Cost = 410.1005
Iteration 17: Best Cost = 410.1005
Iteration 18: Best Cost = 410.1005
Iteration 19: Best Cost = 410.1005
Iteration 20: Best Cost = 410.1005

Code Aplikasi.m:

model=CreateModel();
CostFunction=@(tour) TourLength(tour,model);

nVar=model.n;
MaxIt=20;      % Maximum Number of Iterations
nAnt=40;        % Number of Ants (Population Size)
Q=1;
tau0=10*Q/(nVar*mean(model.D(:))); % Initial Phromone

alpha=1;        % Phromone Exponential Weight
beta=1;         % Heuristic Exponential Weight

rho=0.05;       % Evaporation Rate

eta=1./model.D;             % Heuristic Information Matrix
tau=tau0*ones(nVar,nVar);   % Phromone Matrix
BestCost=zeros(MaxIt,1);    % Array to Hold Best Cost Values

empty_ant.Tour=[];empty_ant.Cost=[];

ant=repmat(empty_ant,nAnt,1);
BestSol.Cost=inf;

for it=1:MaxIt 
    for k=1:nAnt 
        ant(k).Tour=randi([1 nVar]);
     
        for l=2:nVar
            i=ant(k).Tour(end);
            P=tau(i,:).^alpha.*eta(i,:).^beta;
            P(ant(k).Tour)=0;
            P=P/sum(P);
            j=RouletteWheelSelection(P);
            ant(k).Tour=[ant(k).Tour j];   
        end
        ant(k).Cost=CostFunction(ant(k).Tour);
        if ant(k).Cost<BestSol.Cost
            BestSol=ant(k);
        end
     
    end
 
    % Update Phromones
    for k=1:nAnt
        tour=ant(k).Tour;
        tour=[tour tour(1)];
        for l=1:nVar
            i=tour(l);
            j=tour(l+1);
            tau(i,j)=tau(i,j)+Q/ant(k).Cost;
        end
    end
 
 
    tau=(1-rho)*tau;
    % Store Best Cost
    BestCost(it)=BestSol.Cost;
 
    % Show Iteration Information
    disp(['Iteration ' num2str(it) ': Best Cost = ' num2str(BestCost(it))]);
 
    % Plot Solution
    figure(1);
    PlotSolution(BestSol.Tour,model);
    pause(2);%0.01
 
end

%% Results
figure;
plot(BestCost,'LineWidth',2);
xlabel('Iteration');
ylabel('Best Cost');
grid on;



++++++++++++++++++++++++

function model=CreateModel()

    x=[82 91 12 92 63 9 28 55 96 97 15 98 96 49 80 14 42 92 80 96];
    
    y=[66 3 85 94 68 76 75 39 66 17 71 3 27 4 9 83 70 32 95 3];
    
    n=numel(x);
    
    D=zeros(n,n);
    
    for i=1:n-1
        for j=i+1:n
            
            D(i,j)=sqrt((x(i)-x(j))^2+(y(i)-y(j))^2);
            
            D(j,i)=D(i,j);
            
        end
    end
    
    model.n=n;
    model.x=x;
    model.y=y;
    model.D=D;

end

++++++++++++++++++++++++++++++++++++

function L=TourLength(tour,model)

    n=numel(tour);

    tour=[tour tour(1)];
    
    L=0;
    for i=1:n
        L=L+model.D(tour(i),tour(i+1));
    end

end
++++++++++++++++++++++++++++++++++++++


function j=RouletteWheelSelection(P)

    r=rand;
    
    C=cumsum(P);
    
    j=find(r<=C,1,'first');

end

++++++++++++++++++++++++++++++++++++++
function PlotSolution(tour,model)

    tour=[tour tour(1)];
    
    plot(model.x(tour),model.y(tour),'k-o',...
        'MarkerSize',10,...
        'MarkerFaceColor','y',...
        'LineWidth',1.5);
    
    xlabel('x');
    ylabel('y');
    
    axis equal;
    grid on;
    
alpha = 0.1;
    xmin = min(model.x);
    xmax = max(model.x);
    dx = xmax - xmin;
    xmin = floor((xmin - alpha*dx)/10)*10;
    xmax = ceil((xmax + alpha*dx)/10)*10;
    xlim([xmin xmax]);
    
    ymin = min(model.y);
    ymax = max(model.y);
    dy = ymax - ymin;
    ymin = floor((ymin - alpha*dy)/10)*10;
    ymax = ceil((ymax + alpha*dy)/10)*10;
    ylim([ymin ymax]);
    
    
end
++++++++++++++++++++++++++++++++++++++++


GB Phromone 
+++++++++++++++++++++++++++++++++++++++++++++++++++
GB BestRute
+++++++++++++++++++++++++++++++++++++++++++++++++++














Rabu, 05 Februari 2020

SImple Image Processing

https://www.mathworks.com/campaigns/offers/image-segmentation.confirmation.html?s_iid=ans_image-segmentation_370902_rcspot&ab_test=b_version

https://www.mathworks.com/content/dam/mathworks/tag-team/Objects/d/88390_93007v00_Detecting_Cell_Image_Segmentation_2016.pdf


https://www.mathworks.com/matlabcentral/fileexchange/48859-segment-images-interactively-and-generate-matlab-code?s_tid=res_ip_kit3


https://www.mathworks.com/content/dam/mathworks/tag-team/Objects/d/88370_93003v00-detecting-meas-circular-obj-image-2016.pdf


https://www.mathworks.com/content/dam/mathworks/tag-team/Objects/p/88395_93008v00_Texture_Gabor_Filters_2016.pdf

https://www.mathworks.com/help/images/identifying-round-objects.html












Image imfill 'holes' Dan BoundingBox

J = imread('img3.png');
I = rgb2gray(J);
% imshow(I), title('image original grisé');
[~, threshold] = edge(I, 'sobel');
fudgeFactor = .5;
BWs = edge(I,'sobel', threshold * fudgeFactor);
figure, imshow(BWs), title('binary gradient mask');
se90 = strel('line', 3, 90);
se0 = strel('line', 3, 0);
BWsdil = imdilate(BWs, [se90 se0]);
figure, imshow(BWsdil), title('dilated gradient mask');
BWdfill = imfill(BWsdil, 'holes');
figure, imshow(BWdfill);
title('binary image with filled holes');
BWnobord = imclearborder(BWdfill, 4);
figure, imshow(BWnobord), title('cleared border image');
seD = strel('diamond',1);
BWfinal = imerode(BWnobord,seD);
BWfinal = imerode(BWfinal,seD);
figure, imshow(BWfinal), title('segmented image');
BWoutline = bwperim(BWfinal);
Segout = J;
Segout(BWoutline) = 255;
figure,
imshow(Segout), title('outlined original image');




OK


hold on;
labeledImage =BWoutline; %not needed, image should be already in logical
measurements = regionprops(labeledImage, 'BoundingBox');
for k = 1 : length(measurements)
    thisBB = measurements(k).BoundingBox;
    rectangle('Position',[thisBB(1),thisBB(2),thisBB(3),thisBB(4)],'EdgeColor','b','LineWidth',1 );
end



Jika Ingin Langusng di Crop saja objek yang sudah ditemukan tsb:

grayImage = BWoutline;
% Display the image.
imshow(grayImage);
S = regionprops(grayImage,'BoundingBox','Area');
[MaxArea,MaxIndex] = max(vertcat(S.Area));
imshow(grayImage,'InitialMagnification',20)
%// Highlight the required object
hold on
rectangle('Position',S(MaxIndex).BoundingBox,'LineWidth',2,'EdgeColor','y')
Length = S(MaxIndex).BoundingBox(3);
Height = S(MaxIndex).BoundingBox(4);
% Cropping the image
% Get all rows and columns where the image is nonzero
[nonZeroRows,nonZeroColumns] = find(grayImage);
% Get the cropping parameters
topRow = min(nonZeroRows(:));
bottomRow = max(nonZeroRows(:));
leftColumn = min(nonZeroColumns(:));
rightColumn = max(nonZeroColumns(:));
% Extract a cropped image from the original.
croppedImage = grayImage(topRow:bottomRow, leftColumn:rightColumn);
% Display the original gray scale image.
figure
imshow(croppedImage, []);


Selasa, 04 Februari 2020

AutoCrop regionProp


 a = imread('circlesBrightDark.png');
          bw = a > 200;
          imshow(bw)
          title('Image with Circles')

          stats = regionprops('table',bw,'Centroid','MajorAxisLength','MinorAxisLength','BoundingBox');%,'BoundingBox'
           M=stats.BoundingBox;

  mask2=M(3,:);
        croppedImage = imcrop(bw, mask2);
        figure,imshow(croppedImage);title('Cropped Image');

M =

   40.5000  215.5000   69.0000   69.0000
   50.5000   50.5000   99.0000   99.0000
  190.5000  340.5000  115.0000  119.0000




Atau mau seperti ini hasilnya : PAKAI CENTROID


stats =

  3×4 table

        Centroid        BoundingBox     MajorAxisLength    MinorAxisLength
    ________________    ____________    _______________    _______________

        75       250    [1x4 double]    70.016             70.016       
       100       100    [1x4 double]    99.924             99.924       
    242.94    402.67    [1x4 double]    126.23             101.54     


 a = imread('circlesBrightDark.png');
          bw = a > 200;
          imshow(bw)
          title('Image with Circles')
 
          stats = regionprops('table',bw,'Centroid','MajorAxisLength','MinorAxisLength','BoundingBox');%,'BoundingBox'
          centers = stats.Centroid;
          diameters = mean([stats.MajorAxisLength stats.MinorAxisLength],2);
          radii = diameters/2;
 
          % Plot the circles
          hold on
          viscircles(centers,radii);
          hold off
         
++++++++++++++++++++++++



RGB = imread('pillsetc.png');
%imshow(RGB)
I = rgb2gray(RGB);
bw = imbinarize(I);%logical
    %imshow(bw)
    % bw = bwareaopen(bw,30); %logical +NR
    % %imshow(bw)
    % se = strel('disk',2);
    % bw = imclose(bw,se);%logical
    %imshow(bw) 

bw = imfill(bw,'holes');%logical +Fill
imshow(bw)
stats = regionprops('table',bw,'Centroid','MajorAxisLength','MinorAxisLength','BoundingBox');
M=stats.BoundingBox;
hold on
for k = 1:length(M)
    N = M(k,:)
    rectangle('Position',N,'FaceColor','r')
end
+++++++++++++++++++++++++++++



RGB = imread('pillsetc.png');
%imshow(RGB)
I = rgb2gray(RGB);
bw = imbinarize(I);%logical
    %imshow(bw)
    % bw = bwareaopen(bw,30); %logical +NR
    % %imshow(bw)
    % se = strel('disk',2);
    % bw = imclose(bw,se);%logical
    %imshow(bw) 

bw = imfill(bw,'holes');%logical +Fill
imshow(bw)


[B,L] = bwboundaries(bw,'noholes');
imshow(label2rgb(L,@jet,[.5 .5 .5]))
hold on
for k = 1:length(B)
  boundary = B{k};
  plot(boundary(:,2),boundary(:,1),'w','LineWidth',2);
end
+++++++++++++++++++++++++++++++++++++++++++






stats = regionprops(L,'Area','Centroid');
threshold = 0.94;

for k = 1:length(B)

  % obtain (X,Y) boundary coordinates corresponding to label 'k'
  boundary = B{k};

  % compute a simple estimate of the object's perimeter
  delta_sq = diff(boundary).^2;    
  perimeter = sum(sqrt(sum(delta_sq,2)));
  
  % obtain the area calculation corresponding to label 'k'
  area = stats(k).Area;
  
  % compute the roundness metric
  metric = 4*pi*area/perimeter^2;
  
  % display the results
  metric_string = sprintf('%2.2f',metric);

  % mark objects above the threshold with a black circle
  if metric > threshold
    centroid = stats(k).Centroid;
    plot(centroid(1),centroid(2),'ko');
  end
  
 text(boundary(1,2)-35,boundary(1,1)+13,metric_string,'Color','y','FontSize',14,'FontWeight','bold')
  
end

title(['Metrics closer to 1 indicate that ',  'the object is approximately round'])