def main(debug=False):

    ONTO_PATH = "Ontology\\GoalOntoV1.owl"

    MODEL = "model"

    win = GUI(debug)
    win.update()

    cam = io.Camera(host="192.168.1.21", port=9999)
    #cam = tools.CameraEmul("train_test.mp4")

    outputStack = io.OutputStack(host="192.168.1.21", port=9998)
    goalOnto = onto.GoalOnto(ONTO_PATH)
    roomClassification = ctx.RoomClassification(MODEL, 20)
    clockTime = ctx.ClockTime()
    assistanceLevel = cal.TextAssistance()
    decisionKernel = dk.GoalDecisionKernel(goalOnto, assistanceLevel)
    decisionKernel.add(roomClassification, clockTime)

    while win.isOpened():

        for _ in range(1):
            cam.updateFrame()
        decisionKernel.update()
    def train(self, inputArray, outputList):
        '''
        Function to train the classifier.
        1st and 2nd parameters are lists of equal length with data of 256 length vectors and scalars as labels.
        
        (list of vectors of length 256, list of ints) -> ()
        '''
        reducedInputA = IO.SliceDigit(inputArray, outputList, self.digitA)
        reducedInputB = IO.SliceDigit(inputArray, outputList, self.digitB)

        featureA = self.CalculateHeightWidth(reducedInputA)
        featureB = self.CalculateHeightWidth(reducedInputB)

        feature = np.concatenate((featureA, featureB))

        mi = np.amin(feature)
        ma = np.amax(feature)

        nbins = 12
        self.bins = np.linspace(mi, ma, nbins)
        '''
        Plot of the histograms
        '''
        fig, ax = plt.subplots()

        ax.set_ylabel('N')
        ax.set_xlabel('Height/Width')

        plt.hist(featureA, self.bins)
        plt.hist(featureB, self.bins)
        plt.savefig("hist.pdf")
        plt.show()

        #divide by zero is corrected for later so ignore those errors.
        np.seterr(divide='ignore', invalid='ignore')

        conditionalsA = np.bincount(np.digitize(feature, self.bins),
                                    minlength=nbins + 1) / np.bincount(
                                        np.digitize(featureA, self.bins),
                                        minlength=nbins + 1)
        conditionalsB = np.bincount(np.digitize(feature, self.bins),
                                    minlength=nbins + 1) / np.bincount(
                                        np.digitize(featureB, self.bins),
                                        minlength=nbins + 1)

        priorsA = featureA.size / (featureA.size + featureB.size)
        priorsB = featureB.size / (featureA.size + featureB.size)

        PosteriorsA = conditionalsA * priorsA / (conditionalsA * priorsA +
                                                 conditionalsB * priorsB)
        PosteriorsB = conditionalsB * priorsB / (conditionalsA * priorsA +
                                                 conditionalsB * priorsB)

        self.Classifier = np.zeros(len(PosteriorsA))

        for i in range(len(PosteriorsA)):
            if PosteriorsA[i] < PosteriorsB[i]:
                self.Classifier[i] = 0
            elif PosteriorsA[i] > PosteriorsB[i]:
                self.Classifier[i] = 1
    def test(self, inputArray, outputList):
        '''
        Function to test the classifier on the test data.
        1st and 2nd parameters are lists of equal length with data of 256 length vectors and scalars as labels.
        Outputs the accuracy for the digits chosen at initialisation.
        
        (list of vectors of length 256, list of ints) -> (double)
        '''
        reducedInputA = IO.SliceDigit(inputArray, outputList, self.digitA)
        reducedInputB = IO.SliceDigit(inputArray, outputList, self.digitB)

        featureA = self.CalculateHeightWidth(reducedInputA)
        featureB = self.CalculateHeightWidth(reducedInputB)

        ClassifiedA = np.digitize(featureA, self.bins)
        ClassifiedB = np.digitize(featureB, self.bins)

        correctA = 0
        correctB = 0

        for i in range(featureA.size):
            if self.Classifier[ClassifiedA[i]] == 0:
                correctA += 1

        for i in range(featureB.size):
            if self.Classifier[ClassifiedB[i]] == 1:
                correctB += 1

        accuracy = (correctA + correctB) / (featureA.size + featureB.size)

        return accuracy
Пример #4
0
def printMessage(stream, header=None, body=None):
    io = IO.InputOutput()
    io.setStream(stream)
    if header != None:
        io.writeln(data=header + ":")
    if body != None:
        io.writeln(data=body)
    def run(self):
        """
        Return updated indicator.
        """

        if self._h < self._frame_count:

            frame = tools.CameraEmul().getFrame()
            frame = io.Camera().getFrame()

            self._hist[self._h, :, :] = calc_hist([frame], bins=256)
            self._h += 1

            return self._indicator

        else:

            self._h = 0

            probs = self._model.predict(self._hist)
            preds = np.argmax(probs, axis=1)
            pred_hist = np.bincount(preds)

            pred = np.argmax(pred_hist)
            pred = self._classes[pred]

            self.gui.detected['text'] = f"Detected: {pred}"

            return pred
    def parseGoal(self):

        h = self.get(ctx.ClockTime)
        output = io.Text(str(h), (0, 0, 0))

        r = self.get(ctx.RoomClassification)
        output = io.Text(str(r), (0, 0, 0))

        daytime = self._decision_onto.getDaytime(h)
        goals = self._decision_onto.getGoal(daytime=daytime, room=str(r))
        if len(goals) > 0:
            self.goal = str(goals[0].name)
        else:
            self.goal = str(None)

        self.gui.decision['text'] = str(self.goal)
Пример #7
0
 def __init__(self):
     self.InputOutput = InputOutput.InputOutput()
     self.current_byte_state = [0] * 64
     self.raw_input_state = [b'0'] * 64
     self.last_raw_input_state = [b'0'] * 64
     self.reset_state = [b'0'] * 64
     self.last_state = None
     self.moved_piece_index = 64
     self.alive_pieces_off_board = []
     self.dead_pieces_off_board = []
     self.piece_just_moved = None
     self.move_coord = [0] * 2
     self.teams = []
     self.board_map = [[0 for y in range(8)] for x in range(8)]
     self.current_board_pieces = [0] * 64
     self.last_board_pieces = [0] * 66
     self.piece_off_board = False
     self.__FEN_Move = [0] * 2
     self.piece_moved = [0] * 2
     self.initialize_game()
     self.piece_was_placed = False
     self.SQUARE_NAMES = [
         'a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1', 'h2', 'g2', 'f2',
         'e2', 'd2', 'c2', 'b2', 'a2', 'a3', 'b3', 'c3', 'd3', 'e3', 'f3',
         'g3', 'h3', 'h4', 'g4', 'f4', 'e4', 'd4', 'c4', 'b4', 'a4', 'a5',
         'b5', 'c5', 'd5', 'e5', 'f5', 'g5', 'h5', 'h6', 'g6', 'f6', 'e6',
         'd6', 'c6', 'b6', 'a6', 'a7', 'b7', 'c7', 'd7', 'e7', 'f7', 'g7',
         'h7', 'h8', 'g8', 'f8', 'e8', 'd8', 'c8', 'b8', 'a8'
     ]
Пример #8
0
    def notifByOutput(self, notification):

        """
        Put annotation in output stack.
        """

        if self._assistance_level.annotation_type == cal.ANNOTATION_TYPE_TEXT:
            annotation = io.Text(notification, (0,0,2))

        elif self._assistance_level.annotation_type == cal.ANNOTATION_TYPE_SPEAK:
            annotation = io.Speak(notification)

        else:
            annotation = None

        annotation and io.OutputStack().add(annotation)
        io.OutputStack().send()
Пример #9
0
def goToTop(x, y, image):
    width = image.shape[1]

    #store original value for display
    x1 = x
    y1 = y

    #Check x and y are within bounds
    if (x >= width or y >= image.shape[0]):
        cv2.rectangle(image, (x - 2, y - 2), (x + 2, y + 2), 175, -1)
        InputOutput.display_image(image, "GoToTop")
        InputOutput.printWarning("goToTop given invalid x,y: " + str((x, y)) +
                                 " - Dimensions: " + str(image.shape))
        return (x, y)
    else:
        print "GoToTop given valid x,y: " + str((x1, y1))

    #move up until black is found
    maxSearchRadius = 3
    searchRadius = 0

    #if given a black pixel this is a failure
    if (image[y, x] == BLACK):
        InputOutput.printWarning("goToTop given a black pixel)")
        InputOutput.display_image(image, "GoToTop")
        return (x, y)

    while (searchRadius < maxSearchRadius and y > 0
           and x + searchRadius < width and x - searchRadius > 0):
        if image[y - 1, x + searchRadius] != BLACK:
            x = x + searchRadius
            y = y - 1
            searchRadius = 0
        elif image[y - 1, x - searchRadius] != BLACK:
            x = x - searchRadius
            y = y - 1
            searchRadius = 0
        else:
            searchRadius += 1

    #display the starting location and ending location
    cv2.rectangle(image, (x1 - 2, y1 - 5), (x1 + 2, y1 + 2), 75, -1)
    cv2.rectangle(image, (x - 2, y - 2), (x + 2, y + 2), 175, -1)
    InputOutput.display_image(image, "GoToTop")
    return (x, y)
Пример #10
0
def main():
    repeat = True
    while (repeat):
        query = InputOutput.TakeCommand()
        parameters, is_syntax_correct = Interpreter.SyntaxAnalyzer(query)
        if (is_syntax_correct):
            repeat = Interpreter.ImplementOperations(parameters)
        else:
            print("Syntax Error")
    def on_train_begin(self, logs={}):
        self.weights = []

    def on_epoch_end(self, epoch, logs=None):
        self.weights.append(self.model.layers[-1].get_weights()[0])
        
"""
The Tanh function to weightFit to the data.
"""
def TanhFunction(x, a, b, c, beta):
    return ( a*np.tanh(c*(x - beta)) - b)

"""
Load the data set and label list.
"""
lattices = IO.ReadCSV('LatticesCNN.csv')
temperatureLabels = IO.ReadCSV('TemperatureLabelsCNN.csv')

"""
Convert the labels from temperatures to inverse temperatures.
"""
temperatureLabels = 1/temperatureLabels

trainLattices, testLattices, trainLabels, testLabels = train_test_split(lattices,temperatureLabels,train_size = 0.9, test_size = 0.1)

numberClasses = 100
batchSize = len(trainLattices)
numberEpochs = 500

latticeSize = int(len(lattices[0])**(1/2))
Пример #12
0
fx = 843
obj_width = 0.305 #meters

if __name__ == '__main__':
    
    correct_circles = (('OnWater1.jpg',((520,312,100),)),('OnWater3.jpg',((731,416,106),))
        ,('PH2RedBalls.jpg',((519,308,106),(1534,312,106))),('webcamVid1.jpg',((483,413,151),)))
    #correct_circles = (('PH2RedBalls.jpg',((519,308,106),(1534,312,106))),)
    #correct_circles = (('webcamVid1.jpg',((483,413,151),)),)
    circle_comparisons = []
    num_balls = 0 
    for file_name,measur_circle in correct_circles:
        #Keep track of the number of balls measured
        num_balls+= len(measur_circle)   
        
        image = InputOutput.get_image(file_name)
        InputOutput.display_image(image,"Starting Image")
 
        image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert to HSV for thresholding
        image_hsv = cv2.blur(image_hsv, (9,9)) # blur to reduce noise
 
        thresh = ImageProcessing.thresholdRed(image_hsv)
        InputOutput.display_image(thresh,"Thresholded")
        thresh = ImageProcessing.removeNoise(thresh)
        
        calc_circles = ImageProcessing.reflectionDetection(thresh)
        
        #calc_circles = ImageProcessing.getBalls(thresh,4)
        if calc_circles == None:
            calc_circles = []
        #calc_circles = ImageProcessing.get_blob_centroid(image, thresh, 5)
import InputOutput
import utils

files = [
    "a_example.txt", "b_lovely_landscapes.txt", "c_memorable_moments.txt",
    "d_pet_pictures.txt", "e_shiny_selfies.txt"
]
data = InputOutput.Data("input_data/" + files[2])

slides = utils.create_slides(data.photos, 1)

slideshow = [slides.pop(0)]

while slides:  # while slides is not empty
    best_slide_index = 0
    best_score = utils.calculate_score(slideshow[-1][1], slides[0][1])
    for i in range(1, len(slides)):
        score = utils.calculate_score(slideshow[-1][1], slides[i][1])
        if score > best_score:
            best_slide_index = i
            best_score = score

    slideshow.append(slides.pop(best_slide_index))
    print(' '.join([str(x) for x in slideshow[-1][0]]))

output = InputOutput.Output()

for slide in slideshow:
    output.add_slide(-1, slide[0])

output.write("out2.txt")
import InputOutput
import utils

files = [
    "a_example.txt", "b_lovely_landscape.txt", "c_memorable_moments.txt",
    "d_pet_pictures.txt", "e_shiny_selfies.txt"
]
data = InputOutput.Data("input_data/" + files[0])

slides = [
]  # [([photo ids], {tag ids})] each slide is a tuple ([photo ids], {tag ids})
vertical_photos = []

for photo in data.photos:
    if photo[1] == 'h':
        slides.append(
            ([photo[0]],
             set(photo[4])))  # tuple containing ([photo ids], {tag ids})
    else:
        vertical_photos.append(photo)

# vertical photo matchmaking
index = 0
while index + 1 < len(vertical_photos):
    slides.append((
        [vertical_photos[index][0],
         vertical_photos[index + 1][0]],  # the photo ids in this slide
        set(vertical_photos[index][4]).union(set(
            vertical_photos[index + 1][4]))  # the tags in this slide
    ))
Пример #15
0
    def controlUi(self, MainWindow):

        MainWindow.setObjectName("MainWindow")
        #         MainWindow.resize(1000, 550)
        font = QtGui.QFont()
        font.setItalic(True)
        MainWindow.setFont(font)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        #         layout = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents)

        self.gridLayout_centralwidget = QtWidgets.QGridLayout(
            self.centralwidget)

        ######  Instantiating GUI classes

        self.inout_resource_gui = IO_ResourceGUI.InOut_resource(
            self.centralwidget, self.gridLayout_centralwidget)
        self.analysisgui = AnalysisGUI.analyzer(self.centralwidget,
                                                self.gridLayout_centralwidget)
        #         self.gridLayout_centralwidget.addWidget(self.analysisgui, 1, 11, 10, 12)
        self.analysisgui.setEnabled(False)
        self.displaygui = DisplayGUI_Copy1.display()
        self.displaygui.show()
        #self.displaygui = DisplayGUI.display(self.centralwidget)
        self.displaygui.setEnabled(False)

        self.inputoutputcontrol = InputOutput.inputoutput_control()

        #         self.gridLayout_centralwidget.addWidget(self.inout_resource_gui, 1, 1, 4, 10)

        self.image_analyzer = Analysis.ImageAnalyzer(self.analysisgui,
                                                     self.inout_resource_gui)
        #self.ImDisplay = Display.imagedisplayer(self.analysisgui,self.centralwidget)
        self.ImDisplay = Display_Copy1.imagedisplayer(self.analysisgui,
                                                      self.centralwidget,
                                                      self.analysisgui)
        self.PlateGrid = GridLayout.gridgenerator(
            self.centralwidget, self.gridLayout_centralwidget)
        self.PlateGrid.setEnabled(False)

        self.CV_Reader = MetaData_Reader.CellVoyager()

        #         self.setLayout(self.gridLayout_centralwidget)
        MainWindow.setCentralWidget(self.centralwidget)

        ######  Input Output loader controllers

        self.inout_resource_gui.LoadMetadataButton.clicked.connect(
            lambda: self.ON_CLICK_LOADBUTTON(self.inout_resource_gui))
        self.inout_resource_gui.DisplayCheckBox.stateChanged.connect(
            lambda: self.ImDisplay.display_initializer(
                self.Meta_Data_df, self.displaygui, self.inout_resource_gui))

        self.inout_resource_gui.DisplayCheckBox.stateChanged.connect(
            lambda: self.PlateGrid.GRID_INITIALIZER(
                self.Meta_Data_df, self.displaygui, self.inout_resource_gui,
                self.ImDisplay))
        self.PlateGrid.tableWidget.itemClicked.connect(
            lambda: self.PlateGrid.on_click_table(
                self.Meta_Data_df, self.displaygui, self.inout_resource_gui,
                self.ImDisplay))
        self.PlateGrid.FOVlist.itemClicked.connect(
            lambda: self.PlateGrid.on_click_list(self.ImDisplay, self.
                                                 displaygui))
        self.PlateGrid.Zlist.itemClicked.connect(
            lambda: self.PlateGrid.on_click_list(self.ImDisplay, self.
                                                 displaygui))
        self.PlateGrid.Timelist.itemClicked.connect(
            lambda: self.PlateGrid.on_click_list(self.ImDisplay, self.
                                                 displaygui))

        #self.inout_resource_gui.DisplayCheckBox.stateChanged.connect(lambda: INSTANTIATE_DISPLAY())

        ####### Display GUI controlers

        #         self.displaygui.ColScroller.sliderMoved.connect(lambda:
        #                                                         self.ImDisplay.COL_SCROLLER_MOVE_UPDATE(self.displaygui))
        #         self.displaygui.ColSpinBox.valueChanged.connect(lambda:
        #                                                         self.ImDisplay.COL_SPINBOX_UPDATE(self.displaygui))

        #         self.displaygui.RowScroller.sliderMoved.connect(lambda:
        #                                                         self.ImDisplay.ROW_SCROLLER_MOVE_UPDATE(self.displaygui))

        #         self.displaygui.RowSpinBox.valueChanged.connect(lambda:
        #                                                         self.ImDisplay.ROW_SPINBOX_UPDATE(self.displaygui))

        #         self.displaygui.ZScroller.sliderMoved.connect(lambda:
        #                                                       self.ImDisplay.Z_SCROLLER_MOVE_UPDATE(self.displaygui))

        #         self.displaygui.ZSpinBox.valueChanged.connect(lambda:
        #                                                       self.ImDisplay.Z_SPINBOX_UPDATE(self.displaygui))

        #         self.displaygui.FOVScroller.sliderMoved.connect(lambda:
        #                                                         self.ImDisplay.FOV_SCROLLER_MOVE_UPDATE(self.displaygui))
        #         self.displaygui.FOVSpinBox.valueChanged.connect(lambda: self.ImDisplay.FOV_SPINBOX_UPDATE(self.displaygui))

        #         self.displaygui.TScroller.sliderMoved.connect(lambda: self.ImDisplay.T_SCROLLER_MOVE_UPDATE(self.displaygui))
        #         self.displaygui.TSpinBox.valueChanged.connect(lambda: self.ImDisplay.T_SPINBOX_UPDATE(self.displaygui))
        ###### CHANNELS CHECKBOXES
        self.displaygui.Ch1CheckBox.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.displaygui.Ch2CheckBox.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.displaygui.Ch3CheckBox.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.displaygui.Ch4CheckBox.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.displaygui.Ch5CheckBox.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))

        self.displaygui.Ch1maxproject.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.displaygui.Ch2maxproject.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.displaygui.Ch3maxproject.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.displaygui.Ch4maxproject.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.displaygui.Ch5maxproject.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))

        ###### histogram controllers
        self.displaygui.MaxHistSlider.sliderReleased.connect(
            lambda: self.ImDisplay.MAX_HIST_SLIDER_UPDATE(self.displaygui))

        self.displaygui.MinHistSlider.sliderReleased.connect(
            lambda: self.ImDisplay.MIN_HIST_SLIDER_UPDATE(self.displaygui))

        #         self.displaygui.MinHistSpinBox.valueChanged.connect(lambda:
        #                                                             self.ImDisplay.MIN_HIST_SPINBOX_UPDATE(self.displaygui))

        #         self.displaygui.MaxHistSpinBox.valueChanged.connect(lambda:
        #                                                             self.ImDisplay.MAX_HIST_SPINBOX_UPDATE(self.displaygui))

        ####### Nuclei and spot visualization controllers

        self.displaygui.NuclMaskCheckBox.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.analysisgui.NucDetectionSlider.sliderReleased.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.analysisgui.NucSeparationSlider.sliderReleased.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.analysisgui.NucleiAreaSlider.sliderReleased.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))

        self.analysisgui.NucDetectMethod.currentIndexChanged.connect(
            lambda: self.analysisgui.INITIALIZE_SEGMENTATION_PARAMETERS())
        self.analysisgui.NucDetectMethod.currentIndexChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))

        self.displaygui.NucPreviewMethod.currentIndexChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))

        self.displaygui.SpotsCheckBox.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))

        self.analysisgui.SpotCh1CheckBox.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.analysisgui.SpotCh2CheckBox.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.analysisgui.SpotCh3CheckBox.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.analysisgui.SpotCh4CheckBox.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.analysisgui.SpotCh5CheckBox.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))

        ####### Analysis Gui Controllers
        self.batchanalysis = BatchAnalyzer.BatchAnalysis(
            self.analysisgui, self.image_analyzer, self.inout_resource_gui)
        #self.analysisgui.NucMaxZprojectCheckBox.stateChanged.connect(lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.analysisgui.SpotMaxZProject.stateChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.analysisgui.RunAnalysis.clicked.connect(
            lambda: self.batchanalysis.ON_APPLYBUTTON(self.Meta_Data_df))

        self.analysisgui.ResetButton.clicked.connect(
            lambda: self.ON_RESET_BUTTON())
        self.analysisgui.ThresholdSlider.sliderReleased.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.analysisgui.SensitivitySpinBox.valueChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))
        self.analysisgui.spotanalysismethod.currentIndexChanged.connect(
            lambda: self.ImDisplay.GET_IMAGE_NAME(self.displaygui))

        self.analysisgui.ThresholdSlider.sliderReleased.connect(
            lambda: self.image_analyzer.UPDATE_SPOT_ANALYSIS_PARAMS())
        self.analysisgui.SensitivitySpinBox.valueChanged.connect(
            lambda: self.image_analyzer.UPDATE_SPOT_ANALYSIS_PARAMS())
        self.analysisgui.SpotPerChSpinBox.valueChanged.connect(
            lambda: self.image_analyzer.UPDATE_SPOT_ANALYSIS_PARAMS())
        self.analysisgui.spotanalysismethod.currentIndexChanged.connect(
            lambda: self.image_analyzer.UPDATE_SPOT_ANALYSIS_PARAMS())

        self.analysisgui.spotchannelselect.currentIndexChanged.connect(
            lambda: self.image_analyzer.UPDATE_SPOT_ANALYSIS_GUI_PARAMS())
        #  self.analysisgui.CloseButton.clicked.connect(self.closeEvent)
        ##################

        ####### Menu Bar

        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1000, 0))
        self.menubar.setObjectName("menubar")
        self.menuFile = QtWidgets.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.menuTool = QtWidgets.QMenu(self.menubar)
        self.menuTool.setObjectName("menuTool")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionLoad = QtWidgets.QMenu(self.menuFile)
        self.actionLoad.setObjectName("actionLoad")
        self.actionLoad_image = QtWidgets.QAction(self.actionLoad)
        self.actionLoad_image.setObjectName("actionLoad_image")
        self.LoadConfig = QtWidgets.QAction(MainWindow)
        self.LoadConfig.setObjectName("LoadConfig")
        self.saveConfig = QtWidgets.QAction(MainWindow)
        self.saveConfig.setObjectName("saveConfig")
        self.actionexit = QtWidgets.QAction(MainWindow)
        self.actionexit.setObjectName("actionexit")
        self.menuFile.addMenu(self.actionLoad)
        self.actionLoad.addAction(self.actionLoad_image)
        self.menuFile.addAction(self.actionexit)
        self.menuTool.addAction(self.LoadConfig)
        self.menuTool.addAction(self.saveConfig)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuTool.menuAction())

        self.saveConfig.triggered.connect(
            lambda: self.analysisgui.file_save(self.image_analyzer))
        self.LoadConfig.triggered.connect(
            lambda: self.analysisgui.LOAD_CONFIGURATION(self.image_analyzer))

        self.retranslateUi(MainWindow)
        self.analysisgui.AnalysisMode.setCurrentIndex(4)
        self.inout_resource_gui.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Пример #16
0
from sklearn.model_selection import train_test_split

#Settings used to save time if you need to
mode = 3  #used to determine whih dataset we're reading from
read = 0  #change to 1 if you want to re-read dataframes, otherwise, set this to 0
dataWrangle = 1  #change to 1 if you want to rewrangle data
verify = 1  #change to 1 if you want to remake the verification sets
model = 0

if (read):
    currentTime = datetime.datetime.now().isoformat()
    print("Reading time begin:", currentTime)

    print("Reading Training Database, mode {} ...".format(mode))
    trainDF = io.readTrainData(mode)

    print("Reading Test Database...")
    testDF = io.readTestData()

    print("Reading Holiday Database ...")
    holidayDF = io.readHoliday()

    print("Reading item list....")
    itemDF = io.readItemNbr()

    print("Read complete... ")
    finishTime = datetime.datetime.now().isoformat()
    print("Reading time ends:", finishTime)

else:
Пример #17
0
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation 
from matplotlib.animation import FuncAnimation


import InputOutput as IO

def f(x, a, b):
    return x * np.log10(x)

def g(x, a, b):
    return (a + x)^2 + b

brute = IO.ReadCSV("brute.csv")
barnes = IO.ReadCSV("barnes.csv")

nlist = [x[0] for x in barnes[0::2]]
barnes = [x[0] for x in barnes[1::2]]
brute =[x[0] for x in brute[1::2]]

#coefBrute = np.polyfit(nlist,brute,2)
#coefBarnes = np.polyfit(nlist * np.log(nlist)/np.log(8), barnes, 1)

#fitBrute = np.poly1d(coefBrute)
#fitBarnes = np.poly1d(coefBarnes)

a = len(nlist)

#plt.plot(nlist, fitBrute(nlist))
#    def __init__(self, file_list, i_list, genes):
#        threading.Thread.__init__(self)
#
#        self.files = file_list
#        self.indicies = i_list
#        self.genes = genes
#
#    def run(self):
#        for index in range(len(self.files)):
#            print("Start BAM file [",self.indicies[index],"]", file=sys.stderr)
#            Bam.processBam(self.files[index],self.indicies[index],genes)
#            print("End BAM file [",self.indicies[index],"]", file=sys.stderr)
#
THREADING = True

files = InputOutput.getInput(sys.argv,THREADING)

if not files:
    print("usage: python3 FastCount.py <path/to/GTF> <path/to/outfile> <number of threads> <path/to/bamfile_1> <path/to/bamfile_2> <...>")
    sys.exit(1)

thread_num = files['thread']
bams_per_thread = int(len(files['bams']) / int(thread_num))
print("bams per thread",bams_per_thread)

print("Start GTF file", file=sys.stderr)
genes = GTFparse.parseGTFFile(files['gtffile'], len(files['bams']))
print("End GTF file", file=sys.stderr)


Пример #19
0
def VariableSelection(    loadFileName=None,  loadDirName=None, \
                classifierName="linregL2", dataTransformName="getFloatPriceVars", \
                returnTransformName = "passthruVars", etcReturnsName = None,\
                printVarStatsFlag = False,  printClassifierWeightsFlag = False, \
                regDefault = 1.0, regOptRange = None, regSweepRange = None, gamma=None,\
                submissionFileName=None, savePredictionsFileName=None, \
                loadTransformedDataFilename = None, saveTransformedDataFilename=None  ):

    print "\n*** Variable Selection Program ***\n"
    pd = ProvidedData.ProvidedData()
    targetVariable = pd.getTargetVar()
    timestamps = pd.getTimestamps()

    if loadFileName:
        loadedData = loadPredictionsFile(loadFileName)
    elif loadDirName:
        loadedData = loadPredictionsDirectory(loadDirName)
    elif loadTransformedDataFilename:
        loadedData = loadTransformedDataFile(loadTransformedDataFilename)
    else:
        loadedData = None  # assumes transform loads its own data, as some do

    classifier = getClassifier(classifierName,
                               gamma=gamma)  #returns classifier(reg)
    predictProbsFlag = getClassifierPredictProbsFlag(classifierName)

    # transform PRICE data before returns are calculated
    transformDescriptions = getDataTransform(dataTransformName, pd)
    transformDescription = transformDescriptions[0]  #for getFloatPriceVars
    transformedData = transformData(transformDescription, xData=loadedData)

    # get other (fixed) returns to be appended to any returns generated from prices
    # (note: etcReturnsDescription *must* provide it's own data source;
    #        also, return cannot loop, see [0]; only first [[][]] transform list used)
    if etcReturnsName:
        etcReturns = transformData(getDataTransform(etcReturnsName, pd)[0])
    else:
        etcReturns = {}

    # after returns are compiled, possibly do another transform
    returnTransformDescriptions = getDataTransform(returnTransformName, pd)
    returnTransformDescription = returnTransformDescriptions[0]

    priceReturnVars = [
        prDict for prDict in PriceReturnsGenerator(transformedData)
    ]
    etcVars = [dict([item]) for item in etcReturns.items()]
    trialVars = etcVars + priceReturnVars
    selectedVars = {}
    selectedVarsReport = []
    passNum = 0
    thisPassAUC = 0.0
    deltaAUC = 1.0

    while deltaAUC > 0.0001:  # **** HARD CODED IMPROVEMENT? ADD #PASSES TOO???
        bestTrialAUC = 0.0
        bestTrialVar = {}
        passNum += 1
        for trialVar in trialVars:
            # do a transform on the calculated returns data (not prices) in trialVar
            # returnDataTransformed = transformData(returnTransformDescription, \
            #                                             xData = trialVar)
            # trialVar = returnDataTransformed
            # *** commented out above two lines 10/1/2010 for PCA ; moved below trialVarCombo

            if set(trialVar.keys()).intersection(set(selectedVars.keys())):
                print "\nSKIPPING previously selected variable:", trialVar.keys(
                ), "\n"
                continue

            # trialVarCombo = normCenter( dict(selectedVars.items()+trialVar.items()) ) # Worse!
            trialVarCombo = dict(selectedVars.items() +
                                 trialVar.items())  # better
            trialVarCombo = transformData(returnTransformDescription,
                                          xData=trialVarCombo)  #***
            # *** added above 1 line for PCA 10/1/2010

            if printVarStatsFlag:
                printVarStats(trialVarCombo)
            optReg = regDefault
            if regSweepRange:
                optReg = sweepRegularization(regSweepRange, classifier, \
                            trialVarCombo, targetVariable, \
                            predictProbs=predictProbsFlag, yPostProcFunc=None )
            if regOptRange:
                optReg = optimizeRegularization(regOptRange, classifier, \
                            trialVarCombo, targetVariable, \
                            predictProbs=predictProbsFlag, yPostProcFunc=None  )
            # now we have optimum regularization optReg, so predict using that
            print "Optimum regularization to use:", optReg
            optClassifier = classifier(optReg)
            preds = kFoldPrediction( trialVarCombo, targetVariable, \
                                     optClassifier, predictProbs=predictProbsFlag )
            # preds = PostProcessor(preds)   to be implemented??

            auc = AUC(targetVariable, preds)

            if printClassifierWeightsFlag:
                printClassifierWeights(optClassifier, trialVarCombo)
            print "\nRESULTS:  AUC:", auc, "  Reg:", optReg,
            print "  Classifier:", classifierName, "  Transform:", dataTransformName, "\n"

            if auc > bestTrialAUC:
                bestTrialAUC = auc
                bestTrialVar = trialVar
                print "NEW_MAX_AUC:", bestTrialAUC,
                print "DELTA_AUC:", bestTrialAUC - thisPassAUC,
                print "CLASSIFIER:", classifierName,
                print "N_VARS:", len(trialVarCombo.keys())
                print "NEW_MAX_VARS:", sorted(trialVarCombo.keys())
                passPrefix = "pass" + ("%03i" % passNum) + "_"
                if submissionFileName:
                    writeSubmissionFile(timestamps, targetVariable, preds, \
                                                passPrefix + submissionFileName)
                if savePredictionsFileName:
                    savePredictionsFile(preds, \
                                                passPrefix + savePredictionsFileName)
                if saveTransformedDataFilename:
                    saveTransformedDataFile(trialVarCombo, \
                                            passPrefix + saveTransformedDataFilename)
        # /for
        # now have best candidate to add, so add it to the selected list
        selectedVars = dict(selectedVars.items() + bestTrialVar.items())
        bestTrialVarName = bestTrialVar.keys()[0]
        selectedVarsReport.append((bestTrialAUC, bestTrialVarName))
        lastPassAUC = thisPassAUC
        thisPassAUC = bestTrialAUC
        deltaAUC = thisPassAUC - lastPassAUC
        print "\nPASS AUC_IMPROVEMENT:", deltaAUC,
        print "AUC:", thisPassAUC,
        print "CLASSIFIER:", classifierName,
        print "TIME:", InputOutput.localTimeString()
        print "SELECTED VARIABLES AFTER THIS PASS:"******"  ",selectedVarName
        #print
        for passNum, (selectedVarAUC,
                      selectedVarName) in enumerate(selectedVarsReport):
            print "PASS:"******"AUC:", selectedVarAUC, selectedVarName
        print
    # /while
    print "\nProgram finished.\n"
Пример #20
0
# -*- coding: utf-8 -*-
'Python packages'
import numpy as np
import matplotlib.pyplot as plt

'Module created to input data and generate plots'
import InputOutput as IO

'Modules to run the classifiers'
import DistanceClassifier as DC
import BayesClassifier as BC
import Perceptron as P
import GradientDescent as GD

trainInput = IO.Rescale(IO.ReadCSV('train_in.csv'))
trainOutput = IO.ReadCSV('train_out.csv')

testInput = IO.Rescale(IO.ReadCSV('test_in.csv'))
testOutput = IO.ReadCSV('test_out.csv') 

xorInput = np.asarray([[0,0],[0,1],[1,0],[1,1]])
xorOutput = np.asanyarray([0,1,1,0])

'''
Here the classifiers as contructed in the other files are used to run the experiments and generate the plots for the report.
'''

'''
Assignment 1 & 2:
'''
dc = DC.DistanceClassifier()
Пример #21
0
def getBalls(image, sensitivity):
    #Apply the Hough Transform to find the circles
    circles = cv2.HoughCircles(image, cv2.cv.CV_HOUGH_GRADIENT, sensitivity,
                               5)  #2.3 is tp be screwed 2.5 is good

    #/// Apply the Hough Transform to find the circles
    if (circles is None):
        print "Hough transform called but no circles found."
        output = image.copy()
        InputOutput.display_image(np.hstack([image, output]), "houghTransform")
        return circles
    else:
        circlexList = []
        circleyList = []
        circlerList = []
        circleList = []
        circles = np.round(circles[0, :]).astype("int")

        output = image.copy()
        # loop over the (x, y) coordinates and radius of the circles

        Sum_x = 0
        Sum_y = 0
        Sum_r = 0

        count = 0
        for (x, y, r) in circles:
            #get average circle
            if inImage(output, x, y, r):
                count = count + 1
                Sum_x = Sum_x + x  #((ax*count)+x)/(count+1)
                Sum_y = Sum_y + y  #((ay*count)+y)/(count+1)
                Sum_r = Sum_r + r  #((ar*count)+r)/(count+1)
                #avaragedCircle=

                circlexList.append(x)
                circleyList.append(y)
                circlerList.append(r)

                tempCirc = (x, y, r)
                circleList.append(tempCirc)
                # draw the circle in the output image, then draw a rectangle
                # corresponding to the center of the circle

                cv2.circle(output, (x, y), r, (120, 255, 0), 4)
                cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5),
                              (0, 128, 255), -1)

        centeredCircles = kmean.findAvarages(circleList)
        centerCirc1 = centeredCircles[0]
        centerCirc2 = centeredCircles[1]
        radSum = (centerCirc1[2]) + (centerCirc2[2])
        distBetween = kmean.getDistBetween(centerCirc1, centerCirc2)

        print "centeredCircles: " + str(centeredCircles)
        #print "total radius = " + str(radSum)
        #print "distance between = " + str(distBetween)
        if ((distBetween - radSum) <
                0):  # determins is if there is overlap of the 2 circles
            print "1 ball detected"
            ax = Sum_x / count
            ay = Sum_y / count
            ar = Sum_r / count
            circ = (ax, ay, ar)

            #print the average circle
            cv2.circle(output, (ax, ay), ar, (239, 239, 239), 4)
            cv2.rectangle(output, (ax - 5, ay - 5), (ax + 5, ay + 5),
                          (239, 239, 239), -1)
            locationDetection.getDistance(circ)
            locationDetection.getDeg(circ)

            #return the single average circle
            final_circles = ((ax, ay, ar), )

        else:
            print "2 balls detected"

            #print both circles
            cv2.circle(output, (centerCirc2[0], centerCirc2[1]),
                       centerCirc2[2], (239, 239, 239), 4)
            cv2.rectangle(output, (centerCirc2[0] - 5, centerCirc2[1] - 5),
                          (centerCirc2[0] + 5, centerCirc2[1] + 5),
                          (239, 239, 239), -1)
            cv2.circle(output, (centerCirc1[0], centerCirc1[1]),
                       centerCirc1[2], (239, 239, 239), 4)
            cv2.rectangle(output, (centerCirc1[0] - 5, centerCirc1[1] - 5),
                          (centerCirc1[0] + 5, centerCirc1[1] + 5),
                          (239, 239, 239), -1)
            temp = locationDetection.getDistance2balls(centerCirc1,
                                                       centerCirc2)
            locationDetection.getDeg2Circs(centerCirc1, centerCirc2)

            #return the two circles
            final_circles = ((centerCirc1[0], centerCirc1[1], centerCirc1[2]),
                             (centerCirc2[0], centerCirc2[1], centerCirc2[2]))

        # show the output image
        InputOutput.display_image(np.hstack([image, output]), "houghTransform")
        return final_circles
Пример #22
0
                    [obj.NFE / DE.D, obj.pop_fitness[obj.best_vec_index]])
        obj.sorted_pop_indexes = obj.get_sorted_pop_indexes()
        obj.feedback()

    obj.best_vec_index = obj.sorted_pop_indexes[0]
    print(
        f'Model_{Problem.MODEL_NUM} | {obj.ALGO_NAME}: Feasibility = {obj.pop_feasibility[obj.best_vec_index]} | Fitness = {obj.pop_fitness[obj.best_vec_index]}'
    )
    data = {
        'individual': obj.pop[obj.best_vec_index],
        'graphic_info': graphic_info
    }
    return data


if __name__ == '__main__':
    DE_objects = DE_initialization()

    for obj in DE_objects:
        data = DE_steps(obj)
        Report.solution(data['individual'])
        file_name = Problem.get_file_name()
        path = 'results/' + obj.ALGO_FOLDER_NAME + '/model_' + str(
            Problem.MODEL_NUM)
        InputOutput.to_csv(path=path,
                           file_name='individual_' + file_name,
                           data=data['individual'])
        InputOutput.to_csv(path=path,
                           file_name='graphic_info_' + file_name,
                           data=data['graphic_info'])
Пример #23
0
# Aparna Rajpurkar
# This is the central script for the FastCount program, all other .py modules
# except TimetTest.py are DEPENDENCIES.
# imports
import sys
import pysam
import Bam, GTFparse, InputOutput, Reads, Tree

# set threading constant to False--we are not threading in this version
THREADING = False

# check input files and add to a files dictionary
files = InputOutput.getInput(sys.argv, THREADING)

# if something was wrong with the input files, print usage and exit
if not files:
    print(
        "usage: python3 FastCount.py <path/to/GTF> <path/to/outfile> <path/to/bamfile_1> <path/to/bamfile_2> <...>",
        file=sys.stderr)
    sys.exit(1)

# parse the GTF file into a data structure for later use
genes = GTFparse.parseGTFFile(files['gtffile'], len(files['bams']))

# iterate each input BAM file and process it
for i in range(len(files['bams'])):
    # Process BAM file
    Bam.processBam(files['bams'][i], i, genes)
    # output at each BAM file in case there is a crash / for temporary
    # checking out output
    InputOutput.printOutput(files['outfile'] + "_TMP_bamlen_" + str(i), genes,
Пример #24
0
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import InputOutput as IO
"""
Read the files generated by the C# code to plot them in python. 
The number denotes the lattice size the observables were calculated at.
"""
temperatureLabels = IO.ReadCSV('temperatureLabels.csv')

specificHeat8 = IO.ReadCSV('SpecificHeat8.csv')
magnetisation8 = IO.ReadCSV('Magnetisation8.csv')
susceptibility8 = IO.ReadCSV('Susceptibility8.csv')

specificHeat16 = IO.ReadCSV('SpecificHeat16.csv')
magnetisation16 = IO.ReadCSV('Magnetisation16.csv')
susceptibility16 = IO.ReadCSV('Susceptibility16.csv')

specificHeat32 = IO.ReadCSV('SpecificHeat32.csv')
magnetisation32 = IO.ReadCSV('Magnetisation32.csv')
susceptibility32 = IO.ReadCSV('Susceptibility32.csv')

specificHeat128 = IO.ReadCSV('SpecificHeat128.csv')
magnetisation128 = IO.ReadCSV('Magnetisation128.csv')
susceptibility128 = IO.ReadCSV('Susceptibility128.csv')
"""
Reformating the data to comply with pyplot.
"""
specificHeatExpectation8 = [x[0] for x in specificHeat8]
specificHeatError8 = [x[1] for x in specificHeat8]

magnetisationExpectation8 = [x[0] for x in magnetisation8]
Пример #25
0
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import InputOutput as IO

trainInput = IO.Rescale(IO.ReadCSV('train_in.csv'))
trainOutput = IO.ReadCSV('train_out.csv')
'''
This module contains the partially finished code to use the gradient descent for the MNIST set.
Code is not completed so is not run from the main module and has to be run as a separate module.

Code is rough and without comments but functions mirror those as defined for the XOR gradient descent.
'''


def sig(x):
    return 1 / (1 + np.exp(-x))


def tanh(x):
    return (2 / (1 + np.exp(-2 * x))) - 1


def mnist_net(array, weights):
    inputs = np.append(array, 1)

    weights1, weights2 = np.split(weights, [7710])

    weights1 = np.reshape(weights1, (30, 257))
    weights2 = np.reshape(weights2, (10, 31))
Пример #26
0
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation
from matplotlib import rcParams

import InputOutput as IO

#array = IO.ReadCSV("animationcollision.csv")
array = IO.ReadCSV("animationcollision.csv")

xarray = array[0::3]
yarray = array[1::3]
zarray = array[2::3]

rcParams['animation.ffmpeg_path'] = r'C:\Users\Tim\Downloads\ffmpeg-4.1.3-win64-static\ffmpeg-4.1.3-win64-static\bin\ffmpeg.exe'

arrayA = xarray
arrayB = yarray

a = 100

fig, ax = plt.subplots()  
ax.set(xlim=(-a, a), ylim=(-a, a))
ax.set_facecolor('black')
ax.spines['bottom'].set_color('white')
ax.spines['top'].set_color('white') 
ax.spines['right'].set_color('white')
ax.spines['left'].set_color('white')
ax.tick_params(axis='x', colors='white')
Пример #27
0
import matplotlib.pyplot as plt
import os
import bisect
import GaussianMixtureClassifier
import InputOutput
import FeaturesExtraction
import ForgeryDetermination
import Localize
from xlwt import Workbook

# GUI Class
Path = "F:/4th year/Graduation project/Video-Forgery-Detection/Data set/12_forged.avi"
# InputOutput_obj=InputOutput.Input(Path)
# InputOutput_obj=InputOutput.Read()

InputOutput_obj = InputOutput.Read(Path)
InputOutput_obj.ReadVideo()
Video = InputOutput_obj.GetVideo()

FeaturesExtraction_obj = FeaturesExtraction.FeaturesExtraction(Video)
FeaturesExtraction_obj.WaveletDenoising()

FeaturesExtraction_obj.CorrelationCoefficient()
Features = FeaturesExtraction_obj.GetCorrelationCoefficient()
Classify_obj = ForgeryDetermination.Classify(Features)
forged = Classify_obj.GaussianMixture()

if (forged == True):
    Localize_obj = Localize.Localize(Features)
    Localize_obj.Thershold()
    Video, Result = Localize_obj.Localization(Video)
 def run_cmd_interface(self):
     print("*********************************************************")
     print()
     print("Welcome to the Itinerary Management Program")
     print()
     print("*********************************************************")
     print()
     no_exit = True
     while no_exit:
         self.display_menu()
         option = self.choose_option()
         if option == 1:
             print()
             file = input("Enter Name of File in the Input Directory (eg: testroutes.csv):")
             print()
             itineraries = InputOutput(file)
             print()
         elif option == 2:
             try:
                 itineraries.sort_routes(self.calculator,self.airports_info)
                 itineraries.export_routes()
                 print()
                 print("** File entitled 'Itineraries' exported to output directory. Exit menu to access **")
                 print()
             except UnboundLocalError:
                 print("Please load file first using option 1")
                 print()
                 pass
         elif option == 3:
             print()
             code = input("Enter Airport Code:")
             print(self.airports_info.get_airport(code))
             print()
         elif option == 4:
             print()
             country = input("Enter Country Name:")
             print(self.airports_info.get_currency_code(country))
             print()
         elif option == 5:
             print()
             aircraft = input("Enter Aircraft Type:")
             if Aircraft.check_aircraft_type(aircraft) is not False:
                 print()
                 print("The range of",aircraft,"is",Aircraft.check_aircraft_type(aircraft))
             else:
                 print()
                 print("You entered an invalid aircraft type")
             print()
         elif option == 6:
             print()
             code1 = input("Enter 3 Digit Home Airport Code:")
             code2 = input("Enter 3 Digit Destination Airport Code:")
             try:
                 print("Distance between",code1,"and",code2,"is",self.airports_info.get_dist_between_airports(code1,code2),"km")
             except:
                 print("Invalid Code Entered")
             print()
         elif option == 0:
             no_exit = False
     print("*********************************************************")
     print()
     print("You are now existing the Itinerary Management Program")
     print()
     print("*********************************************************")
Пример #29
0
if __name__ == '__main__':
    #img = InputOutput.get_image('Circles.png')
    #InputOutput.display_ima ge(img,'Sample Image')

    #Stores a list of files along with the correct x,y,radius position of any balls
    #filename,((x,y,radius),(x,y,radius)...)
    
    correct_circles = (('OnWater1.jpg',((520,312,100),)),('OnDeck.jpg',((731,416,106),))
        ,('TwoBalls.jpg',((519,308,106),(1534,312,106))))
    circle_comparisons = []
    num_balls = 0
    for file_name,measur_circle in correct_circles:
        #Keep track of the number of balls measured
        num_balls+= len(measur_circle)   
        
        image = InputOutput.get_image(file_name)
        InputOutput.display_image(image,"Starting Image")

        image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert to HSV for thresholding
        image_hsv = cv2.blur(image_hsv, (9,9)) # blur to reduce noise
 
        thresh = ImageProcessing.thresholdRed(image_hsv)
        InputOutput.display_image(thresh,"Thresholded")
        thresh = ImageProcessing.removeNoise(thresh)    
    
        #calc_circles = ImageProcessing.houghTransform(thresh)
        calc_circles = ImageProcessing.blob_circle_detection(thresh)
        if calc_circles == None:
            calc_circles = []
        #calc_circles = ImageProcessing.get_blob_centroid(image, thresh, 5)
         
Пример #30
0
import scipy.io as sio  # pub
import scipy.ndimage as ndimage  # pub
from mayavi import mlab  # pub
import mayavi  # pub
from scipy import spatial  # pub
import numpy as np  # pub
from scipy import spatial  # pub
from scipy import linalg  # pub
from scipy import interpolate

#####  import the data from the local directory ###
PathDicom1 = "/Corner_Solder_Cal"
PathDicom2 = "/Corner_Solder_Cal"

dicom_volume1 = InputOutput.ReadDicom(PathDicom1)
dicom_volume2 = InputOutput.ReadDicom(PathDicom2)

dicom_volume1.loadfiles()
dicom_volume2.loadfiles()

volume1 = dicom_volume1.DicArray  # raw
volume2 = dicom_volume2.DicArray  # raw

## filtering
image1 = ndimage.filters.gaussian_filter(dicom_volume1.DicArray, 3)  # smoothed
image2 = ndimage.filters.gaussian_filter(dicom_volume2.DicArray, 3)  # smoothed

threshold1 = 12000

mode = 5  #used to determine whih dataset we're reading from
read = 0  #change to 1 if you want to re-read dataframes, otherwise, set this to 0
dataWrangle = 0  #change to 1 if you want to rewrangle data
verify = 0  #change to 1 if you want to remake the verification sets
model = 1
predict = 1

if (read):
    currentTime = datetime.datetime.now().isoformat()
    print("Reading time begin:", currentTime)

    print("Reading Training Database, mode {} ...".format(mode))
    #trainDF = io.lesReadTrainData(mode)

    print("Reading Test Database...")
    testDF = io.readTestData()

    print("Reading Holiday Database ...")
    holidayDF = io.readHoliday()

    print("Reading item list....")
    itemDF = io.readItemNbr()

    print("Read complete... ")
    finishTime = datetime.datetime.now().isoformat()
    print("Reading time ends:", finishTime)

else:
    print("Skipping Read...")

if (dataWrangle):
Пример #32
0
def reflectionDetection(image):
    #first find any ball candidates.
    sensitivity = 2.7
    initial_ball_locs = getBalls(image, sensitivity)

    circles = []  #the list of found circles
    if not initial_ball_locs == None:
        for candidate_loc in initial_ball_locs:
            clean_image = image.copy()
            top = goToTop(candidate_loc[0], candidate_loc[1], image)

            #Setup x and y trackers for left and right
            x_left = top[0]
            y_left = top[1]
            x_right = top[0]
            y_right = top[1]

            #Setup tracking positions for reflection detection
            left_farthest = (x_left, y_left)
            right_farthest = (x_right, y_right)

            left_close_pos = (x_left, y_left)
            right_close_pos = (x_right, y_right)
            #constants
            max_step_size = 25
            min_percent_decline = .1

            while (True):
                #the middle x is tracked to allow the left and right trackers to travel farther
                #If a sharp drop off is tracked towards the center the left or right will keep
                #searching until the middle point
                middle_x = (right_farthest[0] + left_farthest[0]) / 2

                #Move one step downward along the edge of the object.
                leftPos = stepDown(image, x_left, y_left, -1, middle_x,
                                   max_step_size)
                rightPos = stepDown(image, x_right, y_right, 1, middle_x,
                                    max_step_size)

                if (leftPos != None and rightPos != None):
                    #Check if both left and right are below their max position this we are on the downslope
                    # of the circle no reason to continue
                    left_declining = (leftPos[0] - left_farthest[0] >
                                      (middle_x - left_farthest[0]) *
                                      (min_percent_decline))
                    right_declining = (right_farthest[0] - leftPos[0] >
                                       (middle_x - right_farthest[0]) *
                                       (min_percent_decline))

                    if (left_declining and right_declining):
                        break

                    left_farthest,right_farthest,left_close_pos,right_close_pos = \
                        updateMinMax(leftPos,rightPos,left_farthest,right_farthest,left_close_pos,right_close_pos)
                    x_left = leftPos[0]
                    y_left = leftPos[1]
                    x_right = rightPos[0]
                    y_right = rightPos[1]
                    cv2.rectangle(clean_image, (x_left - 2, y_left - 2),
                                  (x_left + 2, y_left + 2), 190, -1)
                    cv2.rectangle(clean_image, (x_right - 2, y_right - 2),
                                  (x_right + 2, y_right + 2), 190, -1)
                else:
                    break
            #Display image
            cv2.rectangle(clean_image, (x_left - 2, y_left - 2),
                          (x_left + 2, y_left + 2), 85, -1)
            cv2.rectangle(clean_image, (x_right - 2, y_right - 2),
                          (x_right + 2, y_right + 2), 85, -1)
            InputOutput.display_image(clean_image, "Show Bottom")

            circleX = (right_farthest[0] + left_farthest[0]) / 2
            circleY = (right_farthest[1] + left_farthest[1]) / 2
            circle_radius = (right_farthest[0] - left_farthest[0]) / 2
            circles.append((circleX, circleY, circle_radius))

    print "Output Circles: " + str(circles)
    print "Initial Ball Locations: " + str(initial_ball_locs)
    return circles