Exemple #1
0
    def likeBatchImagesByHashtag(self, hashtag: str, next_max_id: str, api,
                                 network):
        img_size = 200
        if (next_max_id == None):
            api.getHashtagFeed(hashtag)
        else:
            print("getting images with next_max_id:" + next_max_id)
            api.getHashtagFeed(hashtag, next_max_id)
        imgURLs = ImageLoader.getImageURLs(api.LastJson)
        # get next max ID
        next_max_id = ImageLoader.getNextMaxID(api.LastJson)
        img_path = "images/tmp/img.jpg"

        # calculate like probability per image
        for url in tqdm(imgURLs):
            # print(url[0])
            try:
                urllib.request.urlretrieve(url[0], img_path)
            except:
                print("loading of image failed")
            img = dataLoader.load_image(img_path, img_size)
            # tqdm.write("{}: Calculate prediction...".format(datetime.now()))
            probability, str_label, label = network.predict(img)
            # tqdm.write("{0}: Prediction: {1}, Probability: {2:.5f}".format(datetime.now(), str_label, probability))

            if str_label == "like":
                self.like(api, url)
                time.sleep(2)
                if cfg.mode == 2:
                    self.likePicturesByUsername(api, url, network)
                elif cfg.mode == 3:
                    self.likeLikersPictures(api, url, network)

        return next_max_id
    def nextImg(self):
        self.cur_idx += 1
        cur = self.list_idx % self.maxLen
        if cur not in self.img_dict:
            print("Warning: Not in dictionary. Returning previous image")
            worker = ImageLoader.Worker(
                self.loadImg, self.img_list[self.list_idx],
                cur)  # Any other args, kwargs are passed to the run function
            self.threadpool.start(worker)
            self.list_idx += 1
            return self.current
        print("Current: ", self.list_idx, cur, self.img_dict[cur][1])
        img = self.img_dict[cur][0]
        self.current = img

        if self.list_idx < self.vidLen:  # Load new image
            worker = ImageLoader.Worker(
                self.loadImg, self.img_list[self.list_idx],
                cur)  # Any other args, kwargs are passed to the run function
            self.threadpool.start(worker)
            self.list_idx += 1
        else:
            self.list_idx += 1

        return img
Exemple #3
0
def go():
    """
    Takes a picture from the configured camera and displays the image with recognized faces and labels
    Parameters:
    -----------
    None
    
    Returns:
    --------
    None; shows the image with captioned faces
    """
    img = ImageLoader.get_img_from_camera()
    dets = ImageLoader.find_faces(img)
    descs = ImageLoader.find_descriptors(img, dets)
    compared = ImageCompare.compare_faces(descs, database.database)
    draw_faces(dets, compared, img)
Exemple #4
0
 def _readMask(self):
     img = ImageLoader.load(
         self._maskTextureName)  #self.maskTexture.image#.convert("RGBA")
     imgstring = img.convert("RGBA").tostring("raw", "RGBA", 0, 1)
     buffer = array.array('B', imgstring)
     self.maskWidth, self.maskHeight = img.size
     self.mask = buffer
 def load(self, begin=None, end=None):
     if begin == None:
         start = self.list_idx if self.list_idx < self.maxLen else self.list_idx - self.maxLen
         load_len = self.maxLen + start if self.maxLen + start < self.vidLen else self.vidLen
     elif begin != None:
         start = begin
         #if end > self.vidLen:
         #    self.list_idx = start + self.maxLen + 1
         #    return
         if self.list_idx >= self.vidLen:
             self.list_idx = start + self.maxLen + 1
             return
         load_len = start + self.maxLen + 1 if start + self.maxLen + 1 < self.vidLen else self.vidLen
     self.list_idx = start
     img = Image.open(self.img_list[start])
     img = self.prepareImg(img)
     self.current = img
     print("Loading...", start, load_len)
     for i in range(start, load_len):
         worker = ImageLoader.Worker(
             self.loadImg, self.img_list[self.list_idx],
             self.list_idx % self.maxLen
         )  # Any other args, kwargs are passed to the run function
         self.threadpool.start(worker)
         self.list_idx += 1
Exemple #6
0
def add_file(filepath):
    """
    Adds a person to the database given a picture of their face
    Will ask for their name
    
    Parameters
    ----------
    filepath (string):
        the location of the file that is the picture of the person's face
    Returns:
    --------
    None
    """
    img = ImageLoader.get_img_from_file(filepath)
    det = ImageLoader.find_faces(img)
    descriptor = ImageLoader.find_descriptors(img, det)
    database.add_image(descriptor)
Exemple #7
0
def main():
    argv = sys.argv
    if len(argv) > 1:
        if argv[1] == "-youtube":
            url = input("YoutubeのURLを入力してください。")
            yt = YouTube(url)
            name = "download-" + yt.filename
            yt.set_filename(name)
            video = yt.get('mp4')
            video.download("/output/")
            name = "/output/" + name
            print(name)
        else:
            print("Unknown command")
            sys.exit()
    else:
        name = input("動画パスを入力してください。").replace(" ", "")

    #元動画の読み込み
    cap = cv2.VideoCapture(name)
    if not cap.isOpened():
        print("Something wrong...")
        sys.exit()

    retval, frame = cap.read()
    h, w, channels = frame.shape
    # 出力動画の設定
    # 保存ビデオファイルの準備
    # Define the codec and create VideoWriter object
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    rec = cv2.VideoWriter('output.avi', fourcc, 20.0, (w, h))

    # AVIファイルのフレーム数を取得する
    frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

    while (cap.isOpened()):
        ret, frame = cap.read()
        if ret == True:
            frame = im.find(frame, movie=True)
            rec.write(frame)

            # 経過を確認するために100フレームごとに経過を出力
            if cap.get(cv2.CAP_PROP_POS_FRAMES) % 100 == 0:
                date = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
                print(date + '  現在フレーム数:' +
                      str(int(cap.get(cv2.CAP_PROP_POS_FRAMES))) + ' / ' +
                      str(frames),
                      "\r",
                      end="")

        else:
            break
    cap.release()
    rec.release()
    cv2.destroyAllWindows()
def allPlot():  # try me ~ 7 seconds per image
    storage = IL.ImgStorage("../datas/train/")
    imgNB = storage.size() // 3
    fig, axes = plt.subplots(imgNB, 2, figsize=(20, 80))
    for i in range(imgNB):
        print("Computing image ", (i + 1), "out of ", imgNB, "...")
        img = storage.getImgByIndex(i)
        res = cleanWingImg(img)
        axes[i, 0].imshow(img)
        axes[i, 1].imshow(res)
        print("Done.")
    plt.show()
Exemple #9
0
def get_test_data_set():
    '''
    获得测试数据集
    '''
    image_loader = ImageLoader('t10k-images.idx3-ubyte', 10000)
    label_loader = ImageLoader('t10k-labels.idx1-ubyte', 10000)
    return image_loader.load(), label_loader.load()
Exemple #10
0
def get_training_data_set():
    '''
    获得训练数据集
    '''
    image_loader = ImageLoader('train-images.idx3-ubyte', 60000)
    label_loader = ImageLoader('train-labels.idx1-ubyte', 60000)
    return image_loader.load(), label_loader.load()
Exemple #11
0
 def likeLikersPictures(self, api, url, network):
     likers_count = 1
     img_path = "images/tmp/img.jpg"
     api.getMediaLikers(url[1])
     imageLikers = ImageLoader.getImageLikers(api.LastJson)
     for liker in imageLikers:
         if likers_count % 7 == 0:
             return
         elif not liker[1]:  #check if account is private
             if not liker[0] == 321882169:  #check if it is my account
                 self.likeLikersPicture(api, liker[0], network)
                 time.sleep(2)
         likers_count = likers_count + 1
Exemple #12
0
def rawImgToCSV(imgPath, csvPath):
    img = ImageLoader.openPathToNpArray(imgPath)
    print("Cleaning image...")
    cleanedImg = cleanWingImg(img)
    print("computing skeleton...")
    cleanedImg = cleanedImg / 255
    skell = skeletonize(cleanedImg)
    print("keeping centroids...")
    dotsImg = keepGT4(skell)
    print("Computing centroids...")
    centroidList = imageDotsToCentroidList(dotsImg)
    print("Writing to file...")
    centroidList = np.flip(centroidList,axis= 1)
    np.savetxt(csvPath, centroidList, delimiter=",")
    print("Done.")
Exemple #13
0
 def _extractShadowMap(self):
     #shadowMapTex = TextureManager.GetTexture( self.fsPath()+'shadows.png' )
     shadowimage = ImageLoader.load(self.fsPath()+'shadows.png')
     img = shadowimage.convert("RGBA")
     #img = shadowMapTex.image.convert("RGBA")
     imgstring = img.tostring("raw", "RGBA", 0, 1)
     buffer = array.array('B', imgstring)
     self.shadowMapWidth, self.shadowMapHeight = img.size
     self.shadowMap = [1] * (self.shadowMapWidth * self.shadowMapHeight)
     i1 = 0
     i2 = 0
     for y in xrange(self.shadowMapHeight):
         for x in xrange(self.shadowMapWidth):
             self.shadowMap[i1] = buffer[i2] / 255.0
             i1 += 1
             i2 += 4
Exemple #14
0
    def likeLikersPicture(self, api, userId, network):
        img_path = "images/tmp/img.jpg"
        api.getUserFeed(userId)
        userImagesURLs = ImageLoader.getImageURLsByUsername(api.LastJson)
        count_likes = 0
        for url in tqdm(userImagesURLs):
            urllib.request.urlretrieve(url[0], img_path)
            img = dataLoader.load_image(img_path, img_size=200)
            probability, str_label, label = network.predict(img)

            if str_label == "like":
                self.like(api, url)
                time.sleep(2)
                count_likes = count_likes + 1
                if count_likes >= 2:
                    return
def matcher(fingerfile, fp_database, size, savefolder, ImageLoader, cropping,
            sectornorm, gabor2d, match):

    import ImageLoader as IL
    import cropping as cr
    import bob
    import os
    import sectornorm as sn
    import gabor2d as gb2
    import math
    import match as mat
    sp = bob.sp
    np = bob.ip.numpy

    #loads data and saves the fingerprint feature information into a database
    errors = []
    fp_number = len(fp_database)
    f = open(fingerfile, 'r')
    data_files = f.readlines()
    data_names = data_files
    #for imagecount2 in range(0,1):
    for imagecount2 in range(0, len(data_files)):
        toLoad = data_files[imagecount2][0:len(data_files[imagecount2]) - 1]
        print('Loading Image ' + toLoad)
        print('Image number ' + str(imagecount2 + 1) + ' of ' +
              str(len(data_files)))
        #loads selected image into an array and resizes it to be divisible by 8
        loadedImage, height, width = IL.loadImage(toLoad)

        #Crops image around center point
        #print('Cropping image ' + toLoad)
        CroppedPrint, errors = cr.crop(height, width, loadedImage, errors,
                                       toLoad, size)

        #normalizes and sectorizes print
        #print('Sectorizing image ' + toLoad)
        NormalizedPrint, vector = sn.sector_norms(CroppedPrint, 0, 1, size)

        #performs gabor analysis and prepares data to be matched. Fingercode are the features and df is the name of the fingerprint in the database
        fingercode, df = gb2.gabor2d(NormalizedPrint, fp_database, size,
                                     imagecount2, data_names, data_files, 1)

        #matches image against other images.
        best_match = mat.matcher(savefolder, fp_number, data_files,
                                 fp_database, df, fingercode, imagecount2)

    print('complete')
Exemple #16
0
def loadTextures():
    # Configure vars
    global textureNames
    pos = 0
    tempIDs = []
    # For every texture in the list of names, load that file from the textures directory and assign an ID for it
    for name in textureNames:
        ID = glGenTextures(1)
        img_data = ImageLoader.load("Textures/" + name + ".png")
        tempIDs.append((ID, name))
        glBindTexture(GL_TEXTURE_2D, ID)
        glPixelStorei(GL_UNPACK_ALIGNMENT,1)
        glTexImage2D(
            GL_TEXTURE_2D, 0, 3, img_data[0], img_data[1], 0,
            GL_RGBA, GL_UNSIGNED_BYTE, img_data[2]
        )
    return tempIDs
def templatecreator(fingerfile, savefile, size, ImageLoader, cropping,
                    sectornorm, gabor2d):
    import ImageLoader as IL
    import cropping as cr
    import bob
    import os
    import sectornorm as sn
    import gabor2d as gb2
    import pickle
    sp = bob.sp
    np = bob.ip.numpy

    #loads data and saves the fingerprint feature information into a database
    subtract = 0
    errors = []
    fp_database = {}
    f = open(fingerfile, 'r')
    data_files = f.readlines()
    data_names = data_files
    for imagecount in range(0, len(data_names) - subtract):
        #for imagecount in range(0,1):
        toLoad = data_files[imagecount][0:len(data_files[imagecount]) - 1]
        print('Loading Image ' + toLoad)
        print('Image number ' + str(imagecount + 1) + ' of ' +
              str(len(data_names) - subtract))
        #loads selected image into an array and resizes it to be divisible by 8
        loadedImage, height, width = IL.loadImage(toLoad)

        #Crops image around center point
        CroppedPrint, errors = cr.crop(height, width, loadedImage, errors,
                                       toLoad, size)
        #normalizes and sectorizes print
        #print('Sectorizing image ' + toLoad)
        NormalizedPrint, vector = sn.sector_norms(CroppedPrint, 0, 0, size)

        #performs gabor analysis and prepares data to be entered into database
        fp_database, df = gb2.gabor2d(NormalizedPrint, fp_database, size,
                                      imagecount, data_names, data_files, 0)
    #  print('Added to Database fingerprint ' + df)
    pickle.dump(fp_database, open(savefile, 'wb'))

    return data_files, fp_database
def matcher(fingerfile, fp_database,size, savefolder, ImageLoader, cropping, sectornorm, gabor2d, match):

    import ImageLoader as IL
    import cropping as cr
    import bob
    import os
    import sectornorm as sn
    import gabor2d as gb2
    import math
    import match as mat
    sp = bob.sp
    np = bob.ip.numpy

    #loads data and saves the fingerprint feature information into a database
    errors = []
    fp_number = len(fp_database)
    f = open(fingerfile, 'r')
    data_files = f.readlines()
    data_names = data_files
    #for imagecount2 in range(0,1):
    for imagecount2 in range(0,len(data_files)):
        toLoad = data_files[imagecount2][0:len(data_files[imagecount2])-1]
        print('Loading Image '+ toLoad)
        print('Image number ' + str(imagecount2+1) + ' of ' +str(len(data_files)))
	    #loads selected image into an array and resizes it to be divisible by 8
        loadedImage,height,width= IL.loadImage(toLoad)
        
        #Crops image around center point
        #print('Cropping image ' + toLoad)
        CroppedPrint, errors = cr.crop(height,width, loadedImage, errors, toLoad,size)
        
        #normalizes and sectorizes print
        #print('Sectorizing image ' + toLoad)
        NormalizedPrint, vector = sn.sector_norms(CroppedPrint,0,1,size)
        
        #performs gabor analysis and prepares data to be matched. Fingercode are the features and df is the name of the fingerprint in the database
        fingercode, df = gb2.gabor2d(NormalizedPrint,fp_database,size,imagecount2,data_names,data_files,1)
        
        #matches image against other images.
        best_match = mat.matcher(savefolder,fp_number,data_files, fp_database, df, fingercode,imagecount2)
                        
    print('complete')
Exemple #19
0
    def likePicturesByUsername(self, api, url, network):
        like_count_by_user = 0
        img_path = "images/tmp/img.jpg"
        api.getUserFeed(url[2])
        userImagesURLs = ImageLoader.getImageURLsByUsername(api.LastJson)
        for url in tqdm(userImagesURLs):
            urllib.request.urlretrieve(url[0], img_path)
            img = dataLoader.load_image(img_path, img_size=200)
            probability, str_label, label = network.predict(img)

            if str_label == "like":
                self.like(api, url)
                like_count_by_user = like_count_by_user + 1
                time.sleep(2)
        if like_count_by_user >= 4:
            api.follow(url[2])
            print("followed user" + str(url[2]))
            with open('followed_users.txt', 'a') as outfile:
                outfile.write("\n" + str(url[2]))
                outfile.close()
Exemple #20
0
    def __init__(self, dim, start_url):

        self.start_url = start_url

        self.url_frontier = []
        self.url_history = []
        self.img_urls_history = []

        self.image_loader = il.ImageLoader(dim)

        # header object, necessary to get proper response when requesting urls
        self.header = {
            'User-Agent':
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
            'Accept':
            'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Referer': 'https://cssspritegenerator.com',
            'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
            'Accept-Encoding': 'none',
            'Accept-Language': 'en-US,en;q=0.8',
            'Connection': 'keep-alive'
        }
Exemple #21
0
def LoadTextureAdvanced( filename ):
    image = ImageLoader.load(filename)
    ix = image.size[0]
    iy = image.size[1]
    image = image.convert("RGBA")
    img_str = image.tostring("raw", "RGBA", 0, 1)

    # Create Texture
    texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, texture)   # 2d texture (x and y size)

    glPixelStorei(GL_UNPACK_ALIGNMENT,1)
    #glTexImage2D(GL_TEXTURE_2D, 0, 4, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, img_str)
    gluBuild2DMipmaps(GL_TEXTURE_2D, 4, ix, iy, GL_RGBA, GL_UNSIGNED_BYTE, img_str )
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
    GraphicsCard.setTextureAnisotropy( 8.0 )

    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
    return texture, image
Exemple #22
0
def identify(save=True, force_input=False, from_file=False):
    """
    Takes a picture with configured camera and identifies all of the faces in the picture
    Parameters:
    -----------
    save (boolean):
        whether or not to add the captured image to the database
    from_file(boolean):
        whether or not expect a filename instead of taking a picture
    
    Returns:
    --------
    names (list)
        the list of the name of each person in the picture
    """
    if not from_file:
        img = ImageLoader.get_img_from_camera()
        dets = ImageLoader.find_faces(img)
        descs = ImageLoader.find_descriptors(img, dets)
    else:
        filepath = input('Please enter the location (filepath) of the image: ')
        img = ImageLoader.get_img_from_file(filepath)
        dets = ImageLoader.find_faces(img)
        descs = ImageLoader.find_descriptors(img, dets)
    names = ImageCompare.compare_faces(descs, database.database, threshold=0.4)
    if save:
        if len(descs) > 1:
            print("Cannot add multiple people at once.")
        elif len(descs) < 1:
            print("There's no one there!")
        else:
            if force_input:
                database.add_image(descs[0])
            else:
                database.add_image(descs[0], name=names[0])
    draw_faces(dets, names, img)
    return names
Exemple #23
0
path = "./SavedModels/"

print("Following are the list of Files: ")

files = os.listdir(path)
filecount = 0

for i in files:
    print(filecount+1, ")" , i , "\n")
    filecount+=1

print("Enter the number of the Model which you want to load")

num = int(input())

#print("You chose " , files[num-1] )

filehandler = open(path+files[num-1], 'rb')

nn = (pickle.load(filehandler))

training_data, validation_data, test_data = ImageLoader.load_data_wrapper()

for (x, y) in test_data:
    print(np.argmax(nn.feedforward(x)))
    new_im = Image.fromarray((x*255).reshape(28,28))
    new_im.resize((100,100)).show()
    #print(len(x))
    input("Press Enter to go next")
    new_im.close()
	F=f(H)
	fac=255/np.max(F)
	F=F*fac
	F.astype(int)
	print F
	cv2.imshow("skin",blur)
	cv2.waitKey(0)
def HairRemoval(img):
	gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
	hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
	H,S,V=cv2.split(hsv)
	lower=120
	upper=255
	hairs = cv2.adaptiveThreshold(H,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,5,2)
	cv2.imshow("ip2",hairs)
	#cv2.imshow("res",res)
	cv2.waitKey(0)
	Kernal=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
	print(Kernal)
	#return res

	
IL=ImageLoader.Image_Loader()
images=IL.NextSet()
for image in images:
	#res=FeatureDetect(image)
	cv2.imshow("ip",image)
	Skin(image)
	#cv2.imshow("res",res)
	cv2.waitKey(0)
cv2.destroyAllWindows()
Exemple #25
0
    non_trainable_count = np.sum(
        [K.count_params(p) for p in set(model.non_trainable_weights)])

    total_memory = 4.0 * batch_size * (shapes_mem_count + trainable_count +
                                       non_trainable_count)
    gbytes = np.round(total_memory / (1024.0**3), 3)
    return gbytes


K.set_image_dim_ordering('th')
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load data
#(X_train, y_train), (X_test, y_test) = mnist.load_data()
(X_train, y_train) = ImageLoader.loadTrainingImages()
(X_test, y_test) = ImageLoader.loadTestImages()
# reshape to be [samples][pixels][width][height]

wDim = X_train.shape[1]
hDim = X_train.shape[2]

X_train = X_train.reshape(X_train.shape[0], 3, wDim, hDim).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 3, wDim, hDim).astype('float32')
# normalize inputs from 0-255 to 0-1
X_train = X_train / 255
X_test = X_test / 255
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
Exemple #26
0
## Scale 3
#   avg psnr on trainset : 25.90 db
#	avg psnr on testset : 25.75 db

import CONST
import numpy as np
import math
import ImageLoader
import batch_manager
import Image
from scipy import ndimage
from compute_psnr import compute_psnr

dset_train, dset_test, dset_full_gt, dset_full_low = ImageLoader.ImageLoad()

## Batch Manager Instantiation
BM = batch_manager.BatchManager()
BM.init(dset_train, dset_test)

mse_sum = 0
psnr = 0
## Calculate PSNR, MSE of BICUBIC

# bic_batch = BM.testsample()
# nTBATCH = np.shape(bic_batch)[1]
# for i in xrange(nTBATCH):
# 	tmp_bic = bic_batch[1][i,:,:,0] - bic_batch[0][i,:,:,0]
# 	mse = np.mean( np.square(tmp_bic) )
# 	mse_sum = mse_sum + mse
# 	psnr = psnr + 20*math.log10(1.0/math.sqrt(mse+1e-10) )
#
Exemple #27
0
 def _readMask(self):
     img = ImageLoader.load( self._maskTextureName )#self.maskTexture.image#.convert("RGBA")
     imgstring = img.convert("RGBA").tostring("raw", "RGBA", 0, 1)
     buffer = array.array('B', imgstring )
     self.maskWidth, self.maskHeight = img.size
     self.mask = buffer
Exemple #28
0
from keras.utils import np_utils
import  ImageLoader as loader
X_train, X_test, y_train, y_test = loader.loadImages()
new_X_train = X_train.astype('float32')
new_X_test = X_test.astype('float32')
new_X_train /= 255
new_X_test /= 255
new_y_train = np_utils.to_categorical(y_train)
new_y_test = np_utils.to_categorical(y_test)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.optimizers import SGD
from keras.constraints import maxnorm

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(128, 128, 3), activation='relu', padding='same', kernel_constraint=maxnorm(3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu', kernel_constraint=maxnorm(3)))
model.add(Dropout(0.5))
model.add(Dense(6, activation='softmax', kernel_constraint=maxnorm(3)))

model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.05), metrics=['accuracy'])
model.fit(new_X_train, new_y_train, epochs=20, batch_size=32)

import h5py
model.save('Trained Model_SeeFood_new.h5')
Exemple #29
0
fingerfile = '/remote/filer.gx/home.active/dyambay/Bob/FingerprintRec/CrossmatchTrain_Live2.txt'
f = open(fingerfile, 'r')
data_files = f.readlines()
galnames = data_files[0:2]
probenames = data_files[2:4]
galDic,probeDic = ft.createDic(galnames, probenames)
#for x in range(1):
for x in range(0,1):
#for x in range(len(data_files)):
    if x<=1:
        dict_type = 1
    elif x>1:
        dict_type = 2
    toLoad = data_files[x][0:len(data_files[x])-1]
	#loads selected image into an array
    loadedImage, height, width = IL.loadImage(toLoad)
        
    #Crops image around center point
    size = size+16
    CroppedPrint, errors = cr.crop(height, width, loadedImage, errors, toLoad, size)
    cropped = np.asarray(CroppedPrint, dtype='uint8')
    #savetxt = '/idiap/home/dyambay/Bob/Saved Images/CropImage'+str(x)+'.jpg'
    #bob.io.save(cropped,savetxt)
    
	#takes binary image and calculates the orientation field and then extracts ROI based on it
    orientation = frp.orientation(CroppedPrint)
    np.savetxt('/remote/filer.gx/home.active/dyambay/Bob/FingerprintRec/orient' + str(x) +'.txt',orientation)

    '''#uses histogram equalization to enhance the fingerprint image
    enhancedImage = frp.hist_equal(CroppedPrint)
    #savetxt = '/idiap/home/dyambay/Bob/Saved Images/enhanceImage'+str(x)+'.jpg'
Exemple #30
0
#C:\Users\Public\Skin Treatment DIP_ML\code
from theano import *
from theano import tensor as T
import numpy as np
import cv2
import ImageLoader
rad=np.random

row=0
col=0
IL=ImageLoader.Neural_Image_Loader()
def get_Image():
	global row,col
	img,mask=IL.NextSet()
	row,col,chann=img.shape
	x=img.reshape((row*col),chann)
	y=mask.reshape((row*col))
	yp1=y>128
	yp2=y<129
	yp1=yp1*1
	yp2=yp2*1
	yp=np.array([yp1,yp2])
	yp=yp.transpose()
	return x,yp
Xi,Yi=get_Image()
print(Xi,Yi)
rng = np.random.RandomState(1234)
#network sizes
training_steps=1000

#Data input vaiable
Exemple #31
0
def main():
    with open("urls.xml", "rt") as urls:
        for url in urls:
            ImageLoader.load(url, "images")
        ImageAnalyzer.sortImages("images")
Exemple #32
0
from ImageLoader import *

Width = 416  #Width of network's input image
Height = 416  #Height of network's input image

# Give the configuration and weight files for the model and load the network using them.
modelConfiguration = "yolov3.cfg"
modelWeights = "yolov3.weights"

net = cv.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

dataset = ImageLoader()
loader = DataLoader(dataset,
                    batch_size=256,
                    shuffle=False,
                    num_workers=(8 if device == "cuda" else 0))

for idx, (img_names, img_IDs) in enumerate(loader):
    start = time.time()
    img_IDs = img_IDs.numpy()
    imgs = []
    for f in img_names:
        f = os.path.join('data/images/train2014/', f)
        if not os.path.isfile(f):
            print("Input image file ", args.image, " doesn't exist")
            sys.exit(1)
        img = cv.imread(f)