Example #1
0
def getRowsFromImage(image):
    pix_val = list(image.getdata())

    i = 0
    row = []
    rows = []

    el = 0
    for element in pix_val:
        if element[0] == 255:
            el = 0
        else:
            el = 1

        # image.size returns a tuple (width, height)
        if i % image.size[0] == 0 and i != 0:
            rows.append(row)
            row = []
        if i % image.size[0] != 0:
            row.append(el)
        i += 1

    return rows
Example #2
0
 def load_image_into_numpy_array(self, image):
     (im_width, im_height) = image.size
     return np.array(image.getdata()).reshape(
         (im_height, im_width, 3)).astype(np.uint8)
Example #3
0
data = pd.DataFrame(data=content, columns=new_cols)
data.class_name = data.class_name.map({'trafficlight': 1, 'speedlimit': 2, 'crosswalk': 3, 'stop': 4})
print(data.shape)
# data.head()

print("Waiting. . .")
data1 = []

i = 0

for a in data.path_name.values:
    image = Image.open("..\\resources\\" + a).convert("RGB")

    # Image resizing is needed to upgrade the resolution
    image = image.resize((224, 224), Image.ANTIALIAS)
    image = np.array(image.getdata()).reshape(224, 224, 3)
    data1.append(image)

print("---Done---")

X = np.array(data1)

y = np.array(data.iloc[:, -1], dtype=int)

c = to_categorical(y, dtype=int)
Y = c[:, 1:]

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=787)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)

# Layers definition
Example #4
0
def threshold_slow(image):
    #Transformar a imagem em array de bytes
    image_process = np.array(image)
    #Pasta onde fica alojados os arquivos cortados
    path_crop_save = save_path + "/crop/"
    print("Carregando imagem....")
    #Nome padrao para os arquivos
    file_name_save = "/imgpixel"
    text = ""
    #Obtendo a dimenssao da imagem escolhida
    largura, altura = image.size
    #Fazendo o calculo da proporcao
    proporcao = largura / altura
    print("Largura: " + str(largura))
    print("Altura: " + str(altura))
    print("Proporcao: " + str(proporcao))
    #Obtendo o pixel da imagem
    pixels = list(image.getdata())
    numl1 = numl2 = numl3 = numl4 = numl5 = 0
    #print("Pixels: "+str(pixels))
    #Loop para percorrer a imagem
    for y in range(0, altura - 50):
        print('linha', y)
        for x in range(0, largura - 50):
            #Inicialmente e realizado o corte na dimensao de 50x50
            #Crop (Esquerda, cima, direita, baixo)
            new_image = image.crop((x, y, x + 50, y + 50)).copy()
            #A imagem cortada e transformada em array pois o metodo de predicacao so aceita iamgem em array
            crop_img_array = np.array(new_image)
            #Essa nova imagem cortada esta em 3 canais(RGB), com isso e acionado o metodo load
            #para transformar em array e em um canal (graysacle)

            #img_gray = load(new_image)
            img_gray = new_image.convert('L')
            #     img_gray.show()
            time.sleep(0.5)
            img_gray = (np.asarray(img_gray).reshape(1, 50, 50, 1)) / 255.0
            #A ideia e marcar o pixel central, na imagem orignal,da que foi cortada para verificar a execucao
            #com isso ha o metodo threshold no opencv para binarizar a iamgem e posteriormente
            #calcular o momento da binarizacao da imagem, que isto e realizado pelo metodo moments
            # ret,thresh = cv2.threshold(img_gray,127,255,0)
            # M = cv2.moments(thresh)
            image_class = loaded_model.predict(img_gray, verbose=0)
            print(">>>>>>>" + str(image_class))
            #Atribui o valor da classe classificada
            # print(img_gray)
            #exit()
            pred = image_class.argmax(axis=-1)
            ''' Lembrando que o 0 e o numero 7 na regua, bem como
                        o 1 e o 8, 2 e o 13 e o 3 e 14, ja para finalizar
                        4 sao as negativas ou lixo
                        '''

            if pred == 0:
                numl1 = numl1 + 1
                #   time.sleep(0.5)
                #Cada corte e salvo na pasta declarada abaixo para comparar se realmente esta fazendo correto
                crop_write = ""
                crop_write = path_crop_save + "L1/" + file_name_save + "{0}-{1}".format(
                    x, y) + ".jpeg"
                cv2.imwrite(crop_write, crop_img_array)
                #Aqui e localizado o centro da imagem, ou seja, do 50x50 e depois marca com a cor de cada camada
                #declarada, neste caso a verde sao para identificar o numero 7 na regua.
                cX = x + 25
                cY = y + 25
                image_process = cv2.circle(image_process, (cX, cY), 5, verde,
                                           -1)
                cv2.imwrite(save_path + "regua.jpg", image_process)
            elif pred == 1:
                numl2 = numl2 + 1
                #     time.sleep(0.5)
                crop_write = ""
                crop_write = path_crop_save + "L2/" + file_name_save + "{0}-{1}".format(
                    x, y) + ".jpeg"
                cv2.imwrite(crop_write, crop_img_array)
                cX = x + 25
                cY = y + 25
                image_process = cv2.circle(image_process, (cX, cY), 5, amarelo,
                                           -1)
                cv2.imwrite(save_path + "regua.jpg", image_process)
            elif pred == 2:
                numl3 = numl3 + 1
                #         time.sleep(0.5)
                crop_write = ""
                crop_write = path_crop_save + "L3/" + file_name_save + "{0}-{1}".format(
                    x, y) + ".jpeg"
                cv2.imwrite(crop_write, crop_img_array)
                cX = x + 25
                cY = y + 25
                image_process = cv2.circle(image_process, (cX, cY), 5, laranja,
                                           -1)
                cv2.imwrite(save_path + "regua.jpg", image_process)
            elif pred == 3:
                numl4 = numl4 + 1
                #          time.sleep(0.5)
                crop_write = ""
                crop_write = path_crop_save + "L4/" + file_name_save + "{0}-{1}".format(
                    x, y) + ".jpeg"
                cv2.imwrite(crop_write, crop_img_array)
                cX = x + 25
                cY = y + 25
                image_process = cv2.circle(image_process, (cX, cY), 5,
                                           vermelho, -1)
                cv2.imwrite(save_path + "regua.jpg", image_process)
            else:
                #print("Nernhum")
                numl5 = numl5 + 1
                print(str(numl5) + "ยช vez")
                #crop_write = ""
                #crop_write = path_crop_save+"L5/"+file_name_save+"{0}-{1}".format(x,y)+".jpeg"
                #cv2.imwrite(crop_write,crop_img_array)
                #cX=x+25
                #cY=y+25
                #image_process = cv2.circle(image_process, (cX, cY), 5, azul, -1)
                #cv2.imwrite(save_path+"regua.jpg",image_process)

    print(numl1, numl2, numl3, numl4, numl5)
Example #5
0
def cropAndAddPadding(image, newfilepath):

    pix_val = list(image.getdata())


    i = 0
    row = []
    rows= []

    el = 0
    for element in pix_val:
        if element[0] == 255:
            el = 0
        else:
            el = 1
            
        if i % image.size[0] == 0 and i != 0:#image.size returns a tuple (width, height)
            rows.append(row)
            row = []
        if i % image.size[0] != 0: 
            row.append(el)
        i += 1	

    col = []
    cols= []

    for i in range(0,len(rows[0])): #za sekoj chlen od prviot row
        col = []
        for j in range(0,len(rows)): #za sekoj row
            col.append(rows[j][i])
        cols.append(col)
    # Cropping

    cropFromTop = 0
    cropFromBottom = 0
    for row in rows:
        if not(1 in row):
            cropFromTop += 1
        else:
            break

    reversed_rows = rows[::-1]

    for row in reversed_rows:
        if not(1 in row):
            cropFromBottom += 1
        else:
            break

    cropFromLeft = 0
    cropFromRight = 0

    for col in cols:
        if not(1 in col):
            cropFromLeft += 1
        else:
            break

    for col in cols[::-1]:
        if not(1 in col):
            cropFromRight += 1
        else:
            break

    cropped_image = image.crop((cropFromLeft, cropFromTop, image.size[0]-cropFromRight, image.size[1]-cropFromBottom))
    cropped_image.save(newfilepath)
    size = (50, 50)

    resized_image = cropped_image
    padding = 0
    im = cv2.imread(newfilepath)
    color = [255, 255, 255]

    if not (resized_image.size[0] == resized_image.size[1]):
        if resized_image.size[0] > resized_image.size[1]:
            padding = (resized_image.size[0]-resized_image.size[1])//2
            croppedThenPadded = cv2.copyMakeBorder(
                im, padding, padding, 0, 0, cv2.BORDER_CONSTANT, value=color)
        else:
            padding = (resized_image.size[1]-resized_image.size[0])//2
            croppedThenPadded = cv2.copyMakeBorder(
                im, 0, 0, padding, padding, cv2.BORDER_CONSTANT, value=color)
        sv = Image.fromarray(croppedThenPadded)
        sv.save(newfilepath)
        x = sv.resize((size[0], size[1]), Image.LANCZOS)
        x.save(newfilepath)
Example #6
0
def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  # For colored image model: 
  # return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)
  return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)