def segmentation_img(num, i): img = cv2.imread(f'images/ISIC_00{num+i}.jpg') median = cv2.medianBlur(img, 21) grey = cv2.cvtColor(median, cv2.COLOR_BGR2GRAY) grey = cv2.equalizeHist(grey) ## gausiano #binary = cv2.adaptiveThreshold(grey,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\ # cv2.THRESH_BINARY_INV,391,2) # con otsu _, binary = cv2.threshold(grey, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) lista = [2, 3, 5] for j in lista: #iteramos en ventanas de ixi para sacar el ruido de la imagen # se hacen iteraciones para borrar primero los ruidos pequeños # y luego los más grandes que van quedando. kernel = np.ones((j, j), np.uint8) binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel) binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel) # quiza no hacer estos tan grandes, si no que hacerlos chicos, hasta 6 y luego cerrar las ciurvas que se puedan. delete_min_areas(binary) ohter = 255 - binary delete_min_areas(ohter) binary = 255 - ohter cv2.imwrite(f"results/IMG{num+i}EQO.jpg", binary)
def pruebas(num, i): num = 24306 img = cv2.imread(f'images/ISIC_00{num+i}.jpg') img_rbg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) grey = cv2.medianBlur(grey, 31) ret2, th1 = cv2.threshold(grey, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) th2 = cv2.adaptiveThreshold(grey,255,cv2.ADAPTIVE_THRESH_MEAN_C,\ cv2.THRESH_BINARY_INV,437,2) th3 = cv2.adaptiveThreshold(grey,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv2.THRESH_BINARY_INV,437,2) # titles = ['Original Image', 'OTSU THRESHOLDING', # 'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding'] # images = [grey, th1, th2, th3] # for i in range(4): # plt.subplot(2,2,i+1),plt.imshow(images[i],'gray') # plt.title(titles[i]) # plt.xticks([]),plt.yticks([]) # plt.show() delete_min_areas(th2) auxiliar = 255 - th2 delete_min_areas(auxiliar) binary = 255 - auxiliar cv2.imwrite(f"results_jose/IMG{num+i}R.png", binary)
def seg_random_walk(num, i, umbral=85, k=3): """ Funcion que utiliza un umbral y una cantidad de fases para encontrar los marcadores de los puntos destacados de la imagen y genera una segmentación con una imagen binaria """ # lectura de la imagen y blur para los pelos img = cv2.imread(f'images/ISIC_00{num+i}.jpg') img = cv2.medianBlur(img, 21) # Pasamos a blanco y negro y usamos el negativo img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = (255 - img) # matriz que almacenará las fases para el algoritmo marcadores = np.zeros_like(img) # se ocupan 3 fases en torno a nuestro umbral for j in range(k): marcadores[img > umbral + 5 * j] = j + 1 # Aplicamos el algoritmo random walker labels = random_walker(img, marcadores, beta=10) # obtenemos una imagen binaria binary = np.zeros_like(labels) binary[labels >= k] = 255 # eliminamos las areas pequeñas delete_min_areas(binary) # guardamos la imagen cv2.imwrite(f'results/IMG{num+i}RW.jpg', binary)
def kmeans(img, kind, canal = ""): img = cv2.medianBlur(img, 17) if kind == "RBG": img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) elif kind == "HSV": img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) elif kind == "LAB": img = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) if canal != "": H, S, V = cv2.split(img) if canal == 1: printimg(f"canal {canal}", H) Z = H.flatten() elif canal == 2: printimg(f"canal {canal}", S) Z = S.flatten() elif canal == 3: printimg(f"canal {canal}", V) Z = V.flatten() Z = np.float32(Z) else: Z = img.flatten() Z = np.float32(Z) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) ret, label, center = cv2.kmeans(Z, 2, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) # print(f"type_ret: {type(ret)}, type label: {type(label)} shape: {label.shape}, type center: {type(center)} shape: {center.shape} value: {center}") if canal != "": label = np.uint8(label*255) res2 = label.reshape((img.shape[0:2])) else: center = np.uint8(center) res = center[label.flatten()] res = res.reshape((img.shape)) if kind == "RGB": res = cv2.cvtColor(res, cv2.COLOR_RGB2GRAY) if kind == "LAB": res = cv2.cvtColor(res, cv2.COLOR_LAB2RGB) res = cv2.cvtColor(res, cv2.COLOR_RGB2GRAY) if kind == "HSV": res = cv2.cvtColor(res, cv2.COLOR_HSV2RGB) res = cv2.cvtColor(res, cv2.COLOR_RGB2GRAY) _, res2 = cv2.threshold(res, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) delete_min_areas(res2) auxiliar = 255-res2 delete_min_areas(auxiliar) binary = 255-auxiliar count_1 = len(binary[binary == 255]) count_0 = len(binary[binary == 0]) if count_1 > count_0: aux = binary.copy() binary[aux == 255] = 0 binary[aux == 0] = 255 cv2.imshow('binary', binary) return binary
def segmentation_img_gmm(path, a=False, prints=False): img = cv2.imread(path) print_img(f"Imagen original {i}", img, prints) median = cv2.medianBlur(img, 21) print_img("Medianblur de 21x21", median, prints) grey = cv2.cvtColor(median, cv2.COLOR_BGR2GRAY) _, s, v = cv2.split(cv2.cvtColor(median, cv2.COLOR_BGR2HSV)) print_img("Canal s de HSV", s, prints) ## metodo de gausianas multiples de sklearn gmm = GaussianMixture(n_components=2) gmm = gmm.fit(s) threshold = np.mean(gmm.means_) #si utilizamos el canal v el > se debe dar vuelta al otro lado binary_img = s > threshold binary_img = np.uint8(binary_img) * 255 print_img("Imagen binarizada por threshold de gaussian mixture", binary_img, prints) # quitamos areas pequeñas blancas ohter = 255 - binary_img delete_min_areas(ohter) # quitamos areas pequeñas negras binary_img = 255 - ohter delete_min_areas(binary_img) print_img( "Areas pequenas (negras y blancas) eliminadas (gaussian mixture)", binary_img, prints) if a: std_grey = np.std(grey) avg_grey = np.average(grey) adaptive_seg = segmentation_img(path) if std_grey < 13.5 and avg_grey < 170: ## imagenes muy claras funcionan mal con adaptativo. binary_img = binary_img print_img("Resultado", binary_img, prints) else: print_img("Resultado de threshold adaptativo", adaptive_seg, prints) binary_img = np.logical_and(binary_img.flatten(), adaptive_seg.flatten()) binary_img = binary_img.reshape(s.shape) binary_img = np.uint8(binary_img) * 255 print_img( "Logical and entre threshold adaptativo y gaussian mixture", binary_img, prints) return binary_img
def tophat(img): img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) kernel = np.ones((30, 30), np.uint8) blackhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel) tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel) to_rbg = cv2.cvtColor(blackhat, cv2.COLOR_HSV2RGB) to_gray = cv2.cvtColor(to_rbg, cv2.COLOR_RGB2GRAY) h, s, v = cv2.split(blackhat) printimg('tophat', h) # printear_img_plt(s, "s", False) # printear_img_plt(v, "v", False) threshold, binary = cv2.threshold(h, 150, 255, cv2.THRESH_BINARY) delete_min_areas(binary) printimg('tophat', binary)
def histogram_seg(num, i): """ Funcion que recibe el indice de la imagen Estudia el histograma determinando un punto Para determinar un umbral que nos permita segmentar de forma binaria """ # lee la imagen y aplica blur bw img = cv2.imread(f'images/ISIC_00{num+i}.jpg') median = cv2.medianBlur(img, 21) grey = cv2.cvtColor(median, cv2.COLOR_BGR2GRAY) hist, hist_centers = histogram(grey) auxiliar = hist[np.where(hist > np.max(hist) / 4)][0] umbral = hist_centers[list(hist).index(auxiliar)] binary = np.asarray(grey).copy() binary[grey <= umbral] = 255 binary[grey >= umbral] = 0 delete_min_areas(binary) cv2.imwrite('results/IMG{0}H.jpg'.format(num + i), binary)
def segmentation_img_gmm(num, i, a=False): img = cv2.imread(f'images/ISIC_00{num+i}.jpg') median = cv2.medianBlur(img,21) grey = cv2.cvtColor(median, cv2.COLOR_BGR2GRAY) _, s, v = cv2.split(cv2.cvtColor(median, cv2.COLOR_BGR2HSV)) ## metodo de gausianas multiples de sklearn gmm = GaussianMixture(n_components=2) gmm = gmm.fit(s) threshold = np.mean(gmm.means_) #si utilizamos el canal v el > se debe dar vuelta al otro lado binary_img = s > threshold binary_img = np.uint8(binary_img)*255 # quitamos areas pequeñas delete_min_areas(binary_img) ohter = 255-binary_img delete_min_areas(ohter) binary_img = 255-ohter if a: std_grey = np.std(grey) avg_grey = np.average(grey) adaptive_seg = segmentation_img(num, i) if std_grey<13.5 and avg_grey<170: binary_img = binary_img else: binary_img = np.logical_and(binary_img.flatten(), adaptive_seg.flatten()) binary_img = binary_img.reshape(s.shape) binary_img = np.uint8(binary_img)*255 if a: cv2.imwrite(f"results/IMG{num+i}GMMSA.jpg",binary_img) else: cv2.imwrite(f"results/IMG{num+i}GMMS.jpg",binary_img)
import cv2 import numpy as np from matplotlib import pyplot as plt import sklearn from adaptative import delete_min_areas num = 24306 for i in range(50): img = cv2.imread(f'images/ISIC_00{num+i}.jpg') median = cv2.medianBlur(img,21) grey = cv2.cvtColor(median, cv2.COLOR_BGR2GRAY) ret2,binary = cv2.threshold(grey,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) delete_min_areas(binary) ohter = 255-binary delete_min_areas(ohter) binary = 255-ohter cv2.imwrite(f"results/IMG{num+i}O.jpg",binary)