def predict_from_scratch(filepath, data_filename, Xtrain=None, Ytrain=None, knn=None): if Xtrain is None or Ytrain is None: assert knn, "Por favor dar el modelo, o bien los datos Xtrain y Ytrain" # Obtenemos los valores guardados with open(data_filename) as f: data = json.load(f) hdiv = int(data['hdiv']) vdiv = int(data['vdiv']) local_p_clean = np.array(data['p_clean']) local_p_sfs = np.array(data['p_sfs']) # Calculamos las features im = imread(filepath) lbp = lbp_features(im, hdiv=hdiv, vdiv=vdiv) # Filtramos lbp_clean = np.array([lbp[i] for i in local_p_clean]) lbp_sfs = np.array([lbp_clean[i] for i in local_p_sfs]) lbp_sfs = lbp_sfs.reshape(1, -1) if not knn: knn = KNeighborsClassifier(n_neighbors=1) knn.fit(Xtrain, Ytrain) local_pred = knn.predict(lbp_sfs) print(f"La predicción es: {local_pred}")
def add_feats(data, path, im_class): # Se abre el archivo y se convierte en un numpy array. im = imread(path) # Se binariza. im_bin = (im > 140).astype(int) # Se extraen todas las características. hu_feat = hugeo_features(im_bin) flusser_feat = flusser_features(im_bin) fourier_feat = fourier_features(im_bin) # Se crea la fila y se añade la columna de la clase. row = np.concatenate( (hu_feat, flusser_feat, fourier_feat, np.array([im_class]))) # Se añade la fila en el conjunto. if data.shape[0] == 0: return row return np.vstack([data, row])
from pybalu.io import imread from pybalu.feature_extraction import basic_geo from skimage.measure import label import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Ellipse from multiprocessing import Pool im = imread("rice.png") im_bin = (im > 140).astype(int) labeled, n = label(im_bin, return_num=True) plt.figure(figsize=(12, 4.8)) plt.subplot(1, 3, 1) plt.title("Original Image") plt.imshow(im, cmap="gray") def calc_ellipse(idx): region = (labeled == idx).astype(int) feats = basic_geo(region) # feats[0]: center of grav i [px] # feats[1]: center of grav j [px] # feats[10]: MajorAxisLength [px] # feats[11]: MinorAxisLength [px] # feats[12]: Orientation [deg] return np.array([feats[1], feats[0], feats[11], feats[10], -feats[12]]) with Pool() as pool: ellipses = np.vstack(pool.map(calc_ellipse, range(1, n)))
# The following code is used to set up the default parameters for all the # plots shown by matplotlib # %% import matplotlib matplotlib.rcParams["figure.figsize"] = (7, 7) matplotlib.rcParams["axes.titlesize"] = 20 matplotlib.rcParams["axes.titlepad"] = 15 matplotlib.rcParams["figure.figsize"] = (7, 7) del matplotlib # %% [markdown] # ## Loading and displaying the image # %% im = imread("feature_extraction/rice.png") plt.title("Original Image", fontdict={"fontsize": 20}, pad=20) plt.imshow(im, cmap="gray") plt.show() # %% [markdown] # ## Recognizing rice grains # In order to recognize the grains, the following steps are followed: # # 1. Image is transformed to binary # 2. Rice grains are separated and labeled accordingly # 3. Geometric features are calculated for each grain by using `basic_geo_features` function # 4. An `Ellipse` object is built for each grain # %% im_bin = (im > 140).astype(int)
i = 0 for filename in os.listdir(directory): if filename.endswith(".png"): # Para un archivo "face_xxx_nn.png", ID es xxx y nn es nn, ambos en int id_nn = filename[:-4].split("_") ID = int(id_nn[1]) nn = int(id_nn[2]) if ID % 2 == 1: # Nos quedamos con los impares if nn <= 7: # y solo los 7 primeros i += 1 # Leemos la imágen y obtenemos sus features dadas por lbp im = imread(f"{directory}/{filename}") lbp = lbp_features(im, hdiv=hdiv, vdiv=vdiv) # Guardamos los resultados LBPs.append(lbp) IDs.append(ID) NNs.append(nn) if i % 10 == 0: progressBar(i, 350, bar_length=20) print(f"\nLBPs Calculado\nLBP Shape: {len(LBPs)}, {len(LBPs[0])}\nIDs" + f"Shape: {len(IDs)}, 1") # 2) Antes de la selección de features, realizaremos un cleansing con Clean. # Luego realizaremos SFS.