%  Copyright 2018 The MathWorks, Inc.

function [Iori, imgPacked, num, bbox] = myNDNet_Preprocess(inImg)
%#codegen

%% Parameters of input image
sz = size(inImg);
wi = sz(2);
he = sz(1);
ch = sz(3);

ratio = wi*he*ch / 921600;

%% Convert image data format to MATLAB compatible image format
Iori = coder.nullcopy(zeros([he,wi,ch], 'uint8'));
for i = 1:he
    for j = 1:wi
        Iori(i,j,3) = inImg((i-1)*wi*ch + (j-1)*ch+1);
        Iori(i,j,2) = inImg((i-1)*wi*ch + (j-1)*ch+2);
        Iori(i,j,1) = inImg((i-1)*wi*ch + (j-1)*ch+3);
    end
end

%%
gray = rgb2gray(Iori);
gray = imadjust(gray);
hsv = rgb2hsv(Iori);
th = otsuthresh(imhist(hsv(:,:,2)));
bw = hsv(:,:,2) > th;


%bw = imfill(~bw, 'holes');
bw = bwareaopen(~bw, 20000*ratio);

%bw = imerode(bw, strel('diamond', 5));

bwl = bwlabel(bw);
num = max(bwl(:));

% Measure boundingbox of roi instead of using regionprops
bbox = zeros(4);
nuts = coder.nullcopy(zeros([128,128,4], 'uint8'));
if num > 0 && num < 5
    for i = 1:num
        [r, c] = find(bwl == i);
        rmin = min(r);
        rmax = max(r);
        cmin = min(c);
        cmax = max(c);
        bbox(i, :) = [cmin, rmin, cmax-cmin, rmax-rmin];
        tmp = imcrop(gray, bbox(i,:));
        nuts(:,:,i) = imresize(tmp, [128 128]);
    end
else
    num = 0;
end

%% Convert image data format to OpenCV compatible image format

imgPacked = coder.nullcopy(zeros([1,128*128*4], 'uint8'));
for c = 1:4
    for i = 1:128
        for j = 1:128
            imgPacked((i-1)*128 + (j-1) + (c-1)*128*128 + 1) = nuts(i,j,c);
        end
    end
end

end