예제 #1
0
파일: format.py 프로젝트: jher5522/info
def format(birds, content, min, max, avg, location, operator):

	import getImage

	titles = {'link': 'Link',
	'sname':'Scientific Name',
	'cname':'Common Name',
	'dist':'Distribution',
	'mass':'Mass',
	'photo':'Photo'
	}

	#it is important that the content list is in the same order as the birds list
	#must go through them in reverse order so that it doesn't try ot access a postion whic no longer exists once they get suffled down
	for i in range(len(birds)):
		if 'photo' in content:
			photolink = getImage.getImage(birds[i][2])
			birds[i].append(photolink)
		if 'mass' not in content:
			del birds[i][4]
		if 'dist' not in content:
			del birds[i][3]
		if  'link' not in content:
			del birds[i][2]
		if 'sname' not in content:
			del birds[i][1]
		if 'cname' not in content:
			del birds[i][0]

	#create the headrow
	headrow = []
	for key in content:
		headrow.append(titles[key])


	#create a blurb for each condition
	conditions = []
	if min and max:
		conditions.append('mass between ' + str(min) +  'g and ' + str(max) + 'g ')
	elif min:
		conditions.append('mass greater than ' + str(min) + 'g ')
	elif max:
		conditions.append('mass less than ' + str(max) + 'g ')
	if avg:
		conditions.append('average mass of ' + str(avg) + 'g ')
	if location:
		conditions.append('located in ' + location)

	op = ', ' + operator + ' '

	#create a description for each type of result
        if not birds:
                description = "no results to display, try different search terms"
        elif not headrow:
                description = "There are " + str(len(birds)) + " results to your search, but you didn't select any data to display!"
        else:
                description = str(len(birds)) + ' results found. Displaying all birds with: ' + op.join(conditions)

	#return the result
	return [birds, headrow, description]
예제 #2
0
파일: UXBgtk.py 프로젝트: BobBowles/UXBgtk
    def explodeGame(self):
        """
        Make an explosion effect on the screen as the grid is destroyed.
        """

        # obtain the size of the playing area
        size = (self.gridContainer.get_allocated_width(),
                self.gridContainer.get_allocated_height())

        # make the explosion flashImage
        flashImage = getImage('Explosion')
        updateImage(flashImage, 'Explosion', size)
        self.gridContainer.add_with_viewport(flashImage)

        # flash the explosion 5 times
        for i in range(5):

            # display the explosion
            updateImage(self.startImage, 'Click', TOOL_SIZE)
            flashImage.show()
            pause(100)  # wait 200ms without blocking the Gtk event loop

            # hide the explosion
            updateImage(self.startImage, 'Lose', TOOL_SIZE)
            flashImage.hide()
            pause(100)  # wait 200ms without blocking the Gtk event loop

        # ... then destroy the explosion image
        flashImage.destroy()
예제 #3
0
파일: UXBgtk.py 프로젝트: BobBowles/UXBgtk
    def setupStatusBarIcon(self, iconName, imageName):
        """
        Add an icon image to a status bar button.
        """

        icon = self.builder.get_object(iconName)
        image = getImage(imageName)
        updateImage(image, imageName, STATUS_SIZE)
        icon.add(image)
        return icon
예제 #4
0
파일: ededBot.py 프로젝트: iliayar/EdvedBot
def sched_event():
    now = datetime.datetime.now()
    if (now.minute == 0):
        conn = sqlite3.connect('eded.db')

        c = conn.cursor()

        for row in c.execute('SELECT * FROM users'):
            try:
                updater.bot.send_photo(row[0], photo=getImage())
            except:
                delete_user(row[0], c)
        conn.commit()
        conn.close()
    t = threading.Timer(60, sched_event)
    t.start()
예제 #5
0
    def __init__(self, parent=None, pos=None, mined=False):
        """
        Do the class initialization and prepare the game-specific
        attributes.
        """

        super().__init__()

        # the game grid parent
        self.parent = parent

        # give the button a name for css styling
        self.set_name("gridButton")

        # this button's grid position.
        self.pos = pos

        # is this button mined?
        self.mined = mined
        self.exploded = False

        # is this button flagged? - initialize to False
        self.flagged = False

        # initialize the mine count to zero
        self.neighbourMines = 0

        # initialize the neighbour flag count to zero
        self.neighbourFlags = 0

        # flag to emulate disabled when mines are exposed
        self.exposed = False

        # initialize the image to empty at 20 pixels
        self.imageKey = 'Empty'
        self.imageSize = GRID_SIZE
        self.image = getImage(self.imageKey)
        self.add(self.image)
        updateImage(self.image, self.imageKey, self.imageSize)

        # set up the GTK event handlers
        self.connect("button_press_event", self.on_button_press_event)
        self.connect("button_release_event", self.on_button_release_event)
 def run(self):
     self.oddCount = 0
     self.oddList = []
     # load the trained convolutional neural network
     print("[INFO] loading network...")
     self.model = load_model(self.modelFname)
     print "Starting thread"
     while (1):
         imGray = getImage()
         image = cv2.cvtColor(imGray, cv2.COLOR_GRAY2BGR)
         if image is None:
             print 'Error Retrieving Image'
         else:
             odd, self.outImg = self.classifyImage(image, True)
             self.lastTime = datetime.now()
             self.oddList.append(odd)
             if len(self.oddList) > ODD_LIST_LEN:
                 self.oddList = self.oddList[1:]
             self.meanOdd = sum(self.oddList) / len(self.oddList)
             print self.oddList, self.meanOdd
         time.sleep(1)
     print "Exiting Thread"
import datetime
import os

outDir = "./images"


if (os.path.exists(outDir)):
    if (os.path.isdir(outDir)):
        print "Output Directory %s already exists - OK" % outDir
    else:
        print "ERROR:  %s exists, but is not a Directory" % outDir
        exit(-1)
else:
    print "Creating output directory %s" % outDir
    os.makedirs(outDir)



while True:
    frame = getImage()
    if frame is None:
        print 'Error Retrieving Image'
        #exit(-1)
    else:
        tVal = datetime.datetime.now()
        fname = "img_%s.png" % (tVal.strftime("%Y%m%d%H%M%S"))
        print "fname=%s" % (fname)
        cv2.imwrite(os.path.join(outDir,fname),frame)
        
    time.sleep(10)
    print("Number of Odd Images Tested = %d" % nOdd)
    print("Number of Odd Image Errors  = %d" % nOddErr)
    if (nOdd > 0):
        print("  Odd Detection Reliability = %d%%" %
              (100 - int(100 * nOddErr / nOdd)))
    print("")
    print("Number of Normal Images Tested = %d" % nNorm)
    print("Number of Normal Image Errors  = %d" % nNormErr)
    if (nNorm > 0):
        print("  Normal Detection Reliability = %d%%" %
              (100 - int(100 * nNormErr / nNorm)))
    print("")

else:
    while True:
        imGray = getImage()
        #image = np.zeros((IM_SIZE[0],IM_SIZE[1],3), np.uint8)
        image = cv2.cvtColor(imGray, cv2.COLOR_GRAY2BGR)
        if image is None:
            print 'Error Retrieving Image'
        else:
            odd, outimg = classifyImage(model, image, args['gui'])
            if (args['gui']):
                k = cv2.waitKey(1)
                if k == 0x1b:
                    print 'Esc. Exiting'
                    break
            if (odd > 0.5):
                label = "**** ODD *****"
            else:
                label = "Normal"
예제 #9
0
getImage.nClass = 33  #2

height = getImage.height
width = getImage.width
nClass = getImage.nClass

TRAINfolderName = "data/KHimages/train/"
#fileName = "16/resized1A-16X0.png"
# interactive session allows inteleaving of building and running steps
sess = tf.InteractiveSession()

#label, image = getImage.getImage("data/train-00000-of-00001")
#label, image = getImage.getImage("data/train")
#label, image = getImage.getImage(TRAINfolderName + fileName)
label, image = getImage.getImage(TRAINfolderName + "train-00000-of-00001")
#print (label)

print("OK\n")

# and similarly for the validation data

TESTfolderName = "data/KHimages/validate/"
#vlabel, vimage = getImage.getImage("data/validation-00000-of-00001")
vlabel, vimage = getImage.getImage(TESTfolderName +
                                   "/validation-00000-of-00001")

# associate the "label_batch" and "image_batch" objects with a randomly selected batch---
# of labels and images respectively
imageBatch, labelBatch = tf.train.shuffle_batch([image, label],
                                                batch_size=100,
예제 #10
0
 NumberOfImages = 100  # the number of images you want [0-100000]
 colors = [
     'red', 'blue', 'black', 'yellow', 'green', 'red', 'blue', 'black',
     'yellow', 'green'
 ]  # choose a set of colors that gonna be used
 # create output directory
 if not os.path.exists(AggregateOutputPath):
     os.makedirs(AggregateOutputPath)
 # Generate N images and save their information into json file that has the same name as image file
 for idx in range(1, NumberOfImages + 1):
     tag = 'Image(' + str(idx) + ')' + str(uuid.uuid4())
     imageName = tag + '.png'
     jsonfile = tag + '.txt'
     print("Creating Image Number {} of {}".format(idx, NumberOfImages))
     resultFile = os.path.join(AggregateOutputPath, imageName)
     image, canvas = getImage('RGB', (640, 480), 'white')
     #Parameters = [random.choice(['True', 'False']),random.choice(['True', 'False']), random.choice(range(5, 20)), random.choice(range(0,90,5) )]
     Distrotion = 0.1  # for slightly Distorted
     #Distrotion = 0.5  # for heavily Distorted
     Parameters = [
         Distrotion, 'False',
         random.choice(range(5, 20)),
         random.choice(range(0, 90, 5))
     ]
     #Choice = random.choice(range(0,6))
     Choice = 5
     Ver, FunName = Choose_from_Profile(Choice, Parameters)
     print(FunName)
     data = {
         'ImageTag': [{
             "File Name": FunName,
#print(sond.head())

# 2. for now: just use everything as train since i'm using this dummy system anyway.
# 2. (eventually: split into train and test groups)

# 3. loop through train images (using url's from dataframe)
scenScore = [0] * len(sond.index)

for index, row in sond.iterrows():
    imgLink = row['Geograph URI']

    # get the image, always write it to the same file name
    print(imgLink)
    if not "http://www" in imgLink:
        continue
    img = getImage.getImage(imgLink, 'myTest')
    if img == None:
        scenScore[index] = -1
        continue

    # 4. run basic CNN on train images
    probs, classes = run_placesCNN_basic_gen.runBasicCNN()
    totalScore = 0.
    for i in range(len(probs)):

        # 5. for now: assign my scenery score from leighDummyLabels.py according to labels and percentages.
        # 5. (eventually: calculate scenery score based on what that paper did. retrain last layer of CNN?)
        if classes[i] not in leighDummyLabels.leighLabels:
            continue
        thisDummyScore = leighDummyLabels.leighLabels[classes[i]]
        totalScore += float(
예제 #12
0
def gImg0():
    global text
    text += " "
    text += procImg.state
    return getImage()
예제 #13
0
파일: UXBgtk.py 프로젝트: BobBowles/UXBgtk
    def initializeGUI(self):
        """
        Load the main GUI elements from the .glade file.
        """

        self.builder = Gtk.Builder()
        self.builder.add_from_file(UI_BUILD_FILE)
        self.builder.connect_signals(self)

        # these are the toolbar widgets...

        # game start
        self.startButton = self.builder.get_object('startButton')
        self.startImage = getImage('Start')
        updateImage(self.startImage, 'Start', TOOL_SIZE)
        self.startButton.add(self.startImage)

        # hint request
        self.hintButton = self.builder.get_object('hintButton')
        self.hintImage = getImage('Hint')
        updateImage(self.hintImage, 'Hint', TOOL_SIZE)
        self.hintButton.add(self.hintImage)
        self.hintButton.set_sensitive(False)

        # periodic boundary condition toggle
        self.pbcButton = self.builder.get_object('pbcButton')
        self.pbcImage = getImage('PBC_Off')
        updateImage(self.pbcImage, 'PBC_Off', TOOL_SIZE)
        self.pbcButton.add(self.pbcImage)
        self.pbcButton.set_sensitive(True)

        # the configurationBox and its model
        self.configurations = self.builder.get_object('configurations')
        self.configurationBox = self.builder.get_object('configurationBox')

        # an alternative quit button
        self.resetButton = self.builder.get_object('resetButton')
        self.resetImage = getImage('Reset')
        updateImage(self.resetImage, 'Reset', TOOL_SIZE)
        self.resetButton.add(self.resetImage)

        # these are the status bar widgets...

        # ...exposed count
        self.exposedIcon = self.setupStatusBarIcon('exposedIcon', 'Exposed')
        self.exposedCount = self.builder.get_object('exposedCount')
        self.exposedLabel = self.builder.get_object('exposedLabel')

        # ...hint count
        self.hintIcon = self.setupStatusBarIcon('hintIcon', 'Query')
        self.hintCount = self.builder.get_object('hintCount')

        # ...flag count
        self.flagIcon = self.setupStatusBarIcon('flagIcon', 'Flag')
        self.flagCount = self.builder.get_object('flagCount')
        self.flagLabel = self.builder.get_object('flagLabel')

        # the game grid (blank for now)
        self.gridContainer = self.builder.get_object('gridContainer')
        self.gameGrid = None
        self.previousAllocation = self.gridContainer.get_allocation()

        # get references to the toolbar and status bar for size data.
        self.toolbar = self.builder.get_object('toolBox')
        self.statusbar = self.builder.get_object('statusBox')

        # get a reference to the main window itself and display the window
        self.window = self.builder.get_object('window')