def main():
    if (len(sys.argv) > 1) and isinstance(sys.argv[1], str):
        filename = sys.argv[1]
    else:
        filename = 'challenge_video.mp4'

    print('Processing file ' + filename)

    white_output = 'processed_videos/' + filename
    clip1 = VideoFileClip('source_videos/' + filename)  #.subclip(0,5)

    # calculate matrices for perspective transformation
    target_left_x = 300
    target_right_x = 1002
    target_top_y = 0
    target_bottom_y = 690
    src_points = np.float32([[283, 664], [548, 480], [736, 480], [1019, 664]])
    dst_points = np.float32([[target_left_x, target_bottom_y],
                             [target_left_x, target_top_y],
                             [target_right_x, target_top_y],
                             [target_right_x, target_bottom_y]])

    # transformation to bird's eye view
    M = cv2.getPerspectiveTransform(src_points, dst_points)
    # transformation back to normal view
    Mi = cv2.getPerspectiveTransform(dst_points, src_points)

    # calculate or load camera calibration
    calCam = CalibrateCamera.load()

    if calCam == None:
        images = glob.glob('camera_cal/calibration*.jpg')

        calCam = CalibrateCamera()

        calCam.findCorners(images, (9, 6))

        calCam.calibrateCamera()

        calCam.write()

    # class which will process the images, initialize with image size and
    # transformation matrices
    ld = ProcessImage()
    ld.fit((720, 1280), M, Mi, calCam=calCam)

    white_clip = clip1.fl_image(ld.process_image)  # color images

    white_clip.write_videofile(white_output, audio=False)
def DeterminePlayerNames():

    # Take a screenshot
    myScreenShot = pyautogui.screenshot()
    myScreenShot.save(r"images\PlayerNames_File.png")

    # Read Image
    img = ReadImage("PlayerNames_File.png")

    # Cropping for player names
    y=120
    h=700
    x=1650
    w=178
    img = img[y:y+h, x:x+w]

    # Process image
    img = ProcessImage(img)
    # Show
    cv2.imshow('Image', img)
    cv2.waitKey(0)
    cv2.destroyWindow('Image')
    # Text interpret
    text = pytesseract.image_to_string(img)

    # Split and filter text
    text = text.split("\n") # Split text by new lines
    text = [string for string in text if string != ""] # Get rid of empty strings
    player_list = [string for string in text if len(string) > 2] # Get rid of strings < 2 in size (Assumption)

    # Get player names
    #player_list = [string for string in player_list if not string.isdigit()]
    #health_list = [string for string in ]
    print ("Looks like we'll be fighting:")
    print(player_list)
def hitung(filename, perbesaran):
    process = ProcessImage(filename)
    if perbesaran == "40x":
        normal, mikrositik, urledit, filename = process.process()
        return jsonify(
            status="success",
            normal=normal,
            mikrositik=mikrositik,
            urledit=urledit,
            filename=filename)
    elif perbesaran == "100x":
        normal, mikrositik, urledit, filename = process.process2()
        return jsonify(
            status="success",
            normal=normal,
            mikrositik=mikrositik,
            urledit=urledit,
            filename=filename)
def DetermineIfCombat():
    # Find Combat phase
    Combat = 0
    iterator = 0
    max_iter = 50
    while Combat != 1:
        iterator = iterator + 1

        # Take a screenshot
        myScreenShot = pyautogui.screenshot()
        myScreenShot.save(r"images\Phase_File.png")

        # Read in image
        img = ReadImage('Phase_File.png')

        # Debug image file
        #print("DEBUG combat phase file")
        #img = ReadImage('Sample_CombatPhase.png')

        # Cropping
        y = 160
        h = 150
        x = 830
        w = 300
        img = img[y:y + h, x:x + w]

        # Process image
        img = ProcessImage(img)
        # Show
        #cv2.imshow('Image', img)

        # Text interpret
        text = pytesseract.image_to_string(img)

        # Grab Phase
        current_phase = text.split("\n")

        if (current_phase[0] == 'Planning'):
            print("It's' Planning Phase!")

        if (current_phase[0] == 'Combat'):
            print("It's Combat Phase!")
            DetermineOpponent()

        # Wait a little bit
        time.sleep(0.5)

        # Max iterator
        if (iterator == max_iter):
            print("MAX ITERATOR HIT! Quitting...")
            break
Exemplo n.º 5
0
class StoreImage():
    BASE_PATH = os.path.dirname(__file__) + '/person/'

    def __init__(self):
        self.image_processor = ProcessImage()

    def user_exists(self, name):
        if os.path.exists(self.BASE_PATH + name):
            return True

        os.mkdir(self.BASE_PATH + name)
        return False

    def save_image(self, frame, faces, name, counter):
        path = os.path.join(self.BASE_PATH + name + '/')

        frame = self.image_processor.normalize_image(frame, faces)
        cv2.imwrite(path + str(counter) + '.jpg', frame[0])
        return
Exemplo n.º 6
0
def main():
    try:
        start = time.strftime('%m/%d/%Y', time.localtime(time.time() - 86400))
        end = time.strftime('%m/%d/%Y', time.localtime(time.time()))
        all_results = CheckDataUpdate(lat, lon, start, end)
        if len(all_results) == 0:
            print "No data Update"
        else:
            basepath = 'D:\\Data\\Landsat8\\wuhan\\2016\\' + time.strftime(
                '%Y.%m.%d', time.localtime(time.time()))
            DownloadData(basepath, all_results)
            DecompressGzip(basepath)
            ProcessImage(basepath)
            createMxdDocument(r"D:\ly\hb\123456.mxd", basepath)
            Publish(basepath, userName, password, serverName, basepath)
            importDatabase(basepath)
            #basepath='D:\\Data\\Landsat8\\wuhan\\2016\\'+time.strftime('%Y-%m-%d-%H-%I-%M',time.localtime(time.time()))
            #os.makedirs(basepath)
    except Exception as e:
        print("open error: ", e)
Exemplo n.º 7
0
	def __preprocess_file(self,fd):
		if self._image_processor  == None: self._image_processor = ProcessImage(fd)
		else:						       self._image_processor._set_image(fd)
		self._image_processor._calc_histogram_rgb(self._image_processor._get_rgb_image())
		histogram_rgb = self._image_processor._get_histogram_rgb()
		if self._image_statistics == None: self._image_statistics = ImageStatistics(histogram_rgb)
		else:							   self._image_statistics._set_histogram(histogram_rgb)
		mean_rgb 	  = self._image_statistics._get_mean()
		variance_rgb  = self._image_statistics._get_variance(mean_rgb)
		dft_histogram = self._image_processor._get_fourier_transformation()
		self._image_statistics._set_histogram(dft_histogram)
		mean_dft        = self._image_statistics._get_mean()
		variance_dft    = self._image_statistics._get_variance(mean_dft)
		desviation_dft  = self._image_statistics._get_standard_desviation(variance_dft)
		skewness_dft	= self._image_statistics._get_skewness(mean_dft,desviation_dft)
		curtosis_dft    = self._image_statistics._get_curtosis(mean_dft,desviation_dft)
		energy_dft      = self._image_processor._get_fourier_energy()
		mean_difference = self._image_processor._get_histogram_dft_mean_difference()
		feature_vector  = self._image_processor._get_feature_vector(mean_rgb,variance_rgb,mean_dft,variance_dft,skewness_dft,curtosis_dft,energy_dft,mean_difference)
		feature_vector  = self._image_processor._feature_scaling(feature_vector)
		return feature_vector
Exemplo n.º 8
0
    def boot(self):
        self.os_start = time()
        self.number_of_processes = 0

        self.io = IODevice(self.Wait_Queue, self.Ready_Queue)
        self.io.start()

        self.cpu = CPU(self.time_slice)
        with open(self.file_name, 'r') as csvfile:
            processReader = csv.reader(csvfile)

            for row in processReader:
                ID, arrival, priority, program = row
                ID = int(ID)
                arrival = int(arrival)
                priority = int(priority)
                program = program.strip().strip(';')
                program = [int(i) for i in program]
                program = interpret(program)
                process = ProcessImage(ID, arrival, priority, program)
                self.New_Queue.put(process)
                self.number_of_processes += 1
        self.put_in_ready_queue()
Exemplo n.º 9
0
    # st.write("""
    # #
    # """)

    image = st.file_uploader("Podaj obraz zawierający siatkówkę oka")

    if image is not None:
        with open("temp." + extension, "bw") as f:
            f.write(image.read())
        image = imread("temp." + extension)
        remove("temp." + extension)

        st.write("Wybrany obraz")
        st.image(image, use_column_width=True)

        mask = ProcessImage.get_mask(image)

        progress0 = st.progress(0)
        slot0 = st.empty()

        gray = ProcessImage.preprocesing(image, (slot0, []), mask, progress0)
        st.write("Wstępne przetworzenie:")
        st.image(gray, use_column_width=True)

        al_type = __switch.get(algo)

        progress = st.progress(0)
        slot1 = st.empty()

        process = ProcessImage(al_type)
        result = process.process(gray,
Exemplo n.º 10
0
def on_click():
    """
    The main method that is called, when the start button is clicked. It connects to the camera, and calls methods for
    processing the camera image, for maintaining the mode, and for performing an action. In normal mode the actions are
    taken through mouse movements and mouse left clicks, while in 2-gestures mode keyboard events are accomplished.

    :return: none
    """
    global started
    if not started:
        activate_start_button()

        # connect to usb camera
        cap = cv2.VideoCapture(usb_port, cv2.CAP_DSHOW)
        if not cap.isOpened():
            print(
                "WARNING: Failed to connect to usb camera! Connecting to internal camera instead."
            )

            # connect to internal camera
            cap = cv2.VideoCapture(internal_port, cv2.CAP_DSHOW)
            if not cap.isOpened():
                print("ERROR: Failed to connect to internal camera!")
                return

        fps = FPS().start()

        if not cv2.CascadeClassifier(face_model):
            print("ERROR: Failed to load face detector!")
            return

        if not cv2.CascadeClassifier(eye_model):
            print("ERROR: Failed to load eye detector!")
            return

        prev_data = []
        data = []
        click_data = []
        click_counter = 0
        m = MoveMouse(prev_data, data)
        m.center_mouse()

        mode2 = NodShakeMode(prev_data, data)

        while cap.isOpened():
            # capture frame
            ret, rgb_frame = cap.read()

            # end of the stream reached
            if not ret:
                break

            # process camera frame
            img = ProcessImage(rgb_frame)
            img.pre_processing()

            # detect face and eyes
            # data = img.detect_face_and_eyes(cv2.CascadeClassifier(face_model), cv2.CascadeClassifier(eye_model))
            data = img.detect_face_and_eyes_enhanced(
                net, cv2.CascadeClassifier(eye_model))

            if nod_shake_mode:  # navigate only through head-nod and head-shake (two gestures mode)
                mode2.set_data(prev_data, data)
                mode2.apply()

            else:  # normal mode with mouse movement
                # move mouse
                if m.wait_for_click:

                    # collect frames needed
                    if click_counter < clickf:
                        click_data.append(data)
                        click_counter = click_counter + 1
                    else:
                        # analyze mouse clicks
                        m.detect_head_nod(click_data)
                        click_counter = 0
                        click_data = []
                        if m.nod_detected:
                            prev_data = []
                            m.nod_detected = False
                else:
                    m.set_data(prev_data, data)
                    m.move_mouse()
            prev_data.append(data)

            # convert frame to qt format and display image in main window
            set_image_in_main_window(data.frame)

            # display frame in new window
            img = '[LerntiaControl] Kamerabild'
            cv2.imshow(img, data.frame)
            fps.update()

            # stop fps timer
            fps.stop()

            # show/hide FPS information in console if F key is pressed
            global show_fps
            if cv2.waitKey(1) == ord('f'):
                show_fps = not show_fps
            if show_fps:
                # print("INFO: Elapsed time: {:.2f}".format(fps.elapsed()))
                print("INFO: ~FPS: {:.2f}".format(fps.fps()))

            # if ESC, or pause-button pressed, or window closed => release camera handle and close image window
            if cv2.waitKey(
                    1) == 27 or started is False or cv2.getWindowProperty(
                        img, cv2.WND_PROP_VISIBLE) < 1:
                cap.release()
                cv2.destroyAllWindows()
                activate_pause_button()
                break

    else:
        activate_pause_button()
Exemplo n.º 11
0
import os
from ProcessImage import ProcessImage
import numpy as np
import matplotlib.pyplot as plt

prim = ProcessImage()

targetdir = '/Users/mazeyu/newEraFrom2020.5/skinCancer/data/train-2c/melanoma'
targetdir1 = '/Users/mazeyu/newEraFrom2020.5/skinCancer/data/train-2c/nevus'

mel_res = []
for imgpath in os.listdir(targetdir):
    imgpath = os.path.join(targetdir, imgpath)
    print(imgpath, "is processing")
    res = prim(imgpath)
    mel_res.append(res)

ne_res = []
for imgpath in os.listdir(targetdir1):
    imgpath = os.path.join(targetdir1, imgpath)
    res = prim(imgpath)
    ne_res.append(res)

fig, ax = plt.subplots()
ax.plot(np.arange(len(mel_res)), mel_res)
ax.plot(np.arange(len(mel_res)), ne_res[:len(mel_res)])
plt.show()

print(np.average(mel_res), np.median(mel_res), "-->", np.average(ne_res),
      np.median(ne_res))
Exemplo n.º 12
0
 def __init__(self):
     self.image_processor = ProcessImage()
def Style(roi, image, style):
    obj1 = ProcessImage(roi)  # complete, foreground, background
    images = obj1.run_model(image, style)
import cv2
import os
import matplotlib.pyplot as plt

#If it doesn't work Change the Directories in Constants

from utils.constants import *

from ProcessImage import ProcessImage

frame_dir1 = FramesFile + '/' + vid1 + "_" + "FRAME"

images = os.listdir(frame_dir1)

tst = images[0]
tst = cv2.imread(frame_dir1 + '/' + tst)
tst = tst[:, :, ::-1]
'''
def main():
'''
src = cv2.imread(frame_dir1 + '/' + images[0])
img = src.copy()

if __name__ == '__main__':
    #process()
    blur = ProcessImage.Bluring(img)
Exemplo n.º 15
0
import cv2
from WebcamCapture import WebcamCapture
from FaceDetection import FaceDetection
from ProcessImage import ProcessImage
from utils import collect_dataset

images, labels, label_dic = collect_dataset()
rec_lbph = cv2.face.LBPHFaceRecognizer_create()
rec_lbph.train(images, labels)

camera = WebcamCapture()
face_detector = FaceDetection()
image_processor = ProcessImage()

images, labels, label_dic = collect_dataset()

rec_lbph = cv2.face.LBPHFaceRecognizer_create()
rec_lbph.train(images, labels)

rec_eigen = cv2.face.EigenFaceRecognizer_create()
rec_eigen.train(images, labels)

rec_fisher = cv2.face.FisherFaceRecognizer_create()
rec_fisher.train(images, labels)

collector = cv2.face.StandardCollector_create()

frame = camera.get_feed()
faces_area = face_detector.detect_face(frame)

if len(faces_area):
Exemplo n.º 16
0
class StegoDetect:
	
	def __init__(self,train_hidden_path=None,train_no_hidden_path=None,test_path=None,dest_data_path=None,dest_classes_path=None,process=None):
		self._config = Config(train_hidden_path,train_no_hidden_path,test_path,dest_data_path,dest_classes_path,process)
		self._image_processor  = None
		self._image_statistics = None
		self._classificator    = MachineLearning()
		
	def _make_process(self):
		if self._config._get_process()==0: self.__preprocess_corpus()
		else:							   self.__detect_message()
		
	def __preprocess_corpus(self):
		f_data    = open(self._config._get_dest_data_path(),"w")
		f_classes = open(self._config._get_dest_classes_path(),"w")
		for fd in listdir(self._config._get_train_hidden_path()): 
			print fd
			dump(self.__preprocess_file(self._config._get_train_hidden_path()+fd),f_data)
			dump(1,f_classes)
		for fd in listdir(self._config._get_train_no_hidden_path()): 
			print fd
			dump(self.__preprocess_file(self._config._get_train_no_hidden_path()+fd),f_data)
			dump(0,f_classes)
		f_data.close()
		f_classes.close()
		
	def __preprocess_file(self,fd):
		if self._image_processor  == None: self._image_processor = ProcessImage(fd)
		else:						       self._image_processor._set_image(fd)
		self._image_processor._calc_histogram_rgb(self._image_processor._get_rgb_image())
		histogram_rgb = self._image_processor._get_histogram_rgb()
		if self._image_statistics == None: self._image_statistics = ImageStatistics(histogram_rgb)
		else:							   self._image_statistics._set_histogram(histogram_rgb)
		mean_rgb 	  = self._image_statistics._get_mean()
		variance_rgb  = self._image_statistics._get_variance(mean_rgb)
		dft_histogram = self._image_processor._get_fourier_transformation()
		self._image_statistics._set_histogram(dft_histogram)
		mean_dft        = self._image_statistics._get_mean()
		variance_dft    = self._image_statistics._get_variance(mean_dft)
		desviation_dft  = self._image_statistics._get_standard_desviation(variance_dft)
		skewness_dft	= self._image_statistics._get_skewness(mean_dft,desviation_dft)
		curtosis_dft    = self._image_statistics._get_curtosis(mean_dft,desviation_dft)
		energy_dft      = self._image_processor._get_fourier_energy()
		mean_difference = self._image_processor._get_histogram_dft_mean_difference()
		feature_vector  = self._image_processor._get_feature_vector(mean_rgb,variance_rgb,mean_dft,variance_dft,skewness_dft,curtosis_dft,energy_dft,mean_difference)
		feature_vector  = self._image_processor._feature_scaling(feature_vector)
		return feature_vector
	
	def __unpickle(self,fd):
		res = []
		while 1:
			try: 
				res.append(load(fd))
			except EOFError: break
		return res
		
	def __detect_message(self): 
		f_data     = open(self._config._get_dest_data_path(),"rb")
		f_classes  = open(self._config._get_dest_classes_path(),"rb")
		features   = self.__unpickle(f_data)
		classes    = self.__unpickle(f_classes)
		f_data.close()
		f_classes.close()
		## Train ml #
		self._classificator._train(features,classes)
		features = []
		for fd in listdir(self._config._get_test_path()):
			res = self._classificator._test(self.__preprocess_file(self._config._get_test_path()+fd))
			if res==[1]: print "File",fd,"has a hidden message"
			else:        print "File",fd,"has not got any hidden message"