Пример #1
0
    def __init__(self, root, language='es'):
        self.lang = language
        self.root = root
        tk.Frame.__init__(self, self.root)
        # Se llama al canvas
        self.create_frame_canvas()
        # Se crea i18n para internacionalizacion
        self.i18n = I18N(self.lang)
        # Se crea instancia del modelo
        # Se inicializan imagenes del GUI

        self.pnv = Image("photo", file="Resources/PinguinoNoVe.png")
        self.pc = Image("photo", file="Resources/pinguinoChef.png")

        self.img = Image("photo", file="Resources/panque.png")

        self.mas = Image("photo", file="Resources/mas.png")
        # Se establece propidades de root
        self.root.title(self.i18n.title)
        self.root.resizable(1, 1)
        self.root.geometry("1200x700")
        self.root.tk.call('wm', 'iconphoto', self.root._w, self.img)
        # se llama al modulo callbacks
        self.call_backs = Callbacks(self)
        # Se llama a los widgets
        self.create_tabs()
        self.create_menubar()
        self.create_tab1()
        self.create_tab3()
        self.create_logo()
        self.total.set("300")
        self.tab_control.select(2)
Пример #2
0
 def __init__(self, root, parent, lang):
     """
     Primero se busca si existe la carpta de datos (bin) de no ser asi se crea.
     Segundo de busca si existe el archivo index.bin en la carpeta de datos, de no ser asi se crea.
     Al final se lee el archivo index y se establece el atributo current_index con el valor del
     archivo index.
     atributos:
     self.gui = parent es el parent del gui principal
     self.index es la bandera que marca si existe o no un index. Por defecto se inicia en False
     self.root_dir es el directorio actual donde se ejjecuta el projecto
     self.dirs es el nombre de la carpeta de datos
     self.dir_models es la ruta absoluta de la carpeta de datos
     """
     self.root = root
     self.gui = parent
     self.i18n = I18N(lang)
     self.index = False
     self.current_index = []
     self.root_dir = os.path.dirname(os.path.abspath(__file__))
     self.dirs = 'bin'
     self.search_or_make_dir('', self.dirs)
     self.dir_models = os.path.join(self.root_dir, self.dirs)
     self.search_index()
     self.load_index()
     self.pcbi = Image("photo", file="Resources/pinguinoChefPanbien.png")
     self.pcqi = Image("photo", file="Resources/pinguinoChefPanQuemado.png")
     self.lpzi = Image("photo", file="Resources/lapiz.png")
     self.ojoi = Image("photo", file="Resources/ojo.png")
Пример #3
0
    def encoding(self):
        encode(self.fileLocation, self.encodeData, self.outputFileName)

        messagebox.showinfo(
            "Complete",
            'Steganographier have encrypted the image successfully! The file is located at  \n'
            + self.outputFileName)

        self.lblProgramName['text'] = "Encryption Completed"
        self.lblSelectText.lower(self.frame)
        self.lblOutputFileName.lower(self.frame)
        self.lblShowSelectInput.lower(self.frame)
        self.btnNextProcess.lower(self.frame)
        self.textOutputFileName.lower(self.frame)

        originalImg = Image.open(self.fileLocation)
        # resize the image and apply a high-quality down sampling filter
        originalImg = originalImg.resize((210, 210), Image.ANTIALIAS)
        # PhotoImage class is used to add image to widgets, icons etc
        originalImg = ImageTk.PhotoImage(originalImg)
        self.lblShowOriginal = tk.Label(self.root,
                                        image=originalImg,
                                        bg="white")
        self.lblShowOriginal.image = originalImg
        self.lblShowOriginal.place(relwidth=0.3,
                                   relheight=0.3,
                                   relx=0.15,
                                   rely=0.35)

        # opens the image
        encryptImg = Image.open(self.outputFileName)
        # resize the image and apply a high-quality down sampling filter
        encryptImg = encryptImg.resize((210, 210), Image.ANTIALIAS)
        # PhotoImage class is used to add image to widgets, icons etc
        encryptImg = ImageTk.PhotoImage(encryptImg)
        self.lblShowEncrypted = tk.Label(self.root,
                                         image=encryptImg,
                                         bg="white")
        self.lblShowEncrypted.image = encryptImg
        self.lblShowEncrypted.place(relwidth=0.3,
                                    relheight=0.3,
                                    relx=0.55,
                                    rely=0.35)

        self.lblOriginalText = tk.Label(text="Original Photo",
                                        font=("Helvetica", 16),
                                        bg="white")
        self.lblOriginalText.place(relwidth=0.3,
                                   relheight=0.08,
                                   relx=0.15,
                                   rely=0.65)
        self.lblEncryptedText = tk.Label(text="Encrypted Photo",
                                         font=("Helvetica", 16),
                                         bg="white")
        self.lblEncryptedText.place(relwidth=0.3,
                                    relheight=0.08,
                                    relx=0.55,
                                    rely=0.65)
        self.btnHome.lift(self.frame)
 def save(self):
     self.drawWindow.destroy()
     filename = 'image.png'  # image_number increments by 1 at every save
     self.image1.save(filename)
     img = Image.open(filename)
     img = self.process_img(img)
     idx = model.predict(img)
     print(idx)
     showImage = Image.open('letters/' + str(idx) + '.png')
     showImage.show()
Пример #5
0
def anonmeyes(imagepath, picture):
    picture = os.path.join(imagepath, picture)
    image = Image.open(picture)
    data = list(image.getdata())
    image_no_exif = Image.new(image.mode, image.size)
    image_no_exif.putdata(data)
    randomstring = str(uuid.uuid4())

    filename = os.path.join(imagepath + '/cleaned', randomstring + '.png')

    image_no_exif.save(filename)

    prototxtPath = resource_path("deploy.prototxt")
    weightsPath = resource_path("res10_300x300_ssd_iter_140000.caffemodel")
    net = cv2.dnn.readNet(prototxtPath, weightsPath)

    # load the input image from disk, clone it, and grab dimensions
    image.close()
    image = cv2.imread(filename)
    orig = image.copy()
    (h, w) = image.shape[:2]

    # construct a blob from the image
    blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300), (104.0, 177.0, 123.0))

    net.setInput(blob)
    detections = net.forward()

    # loop over the detections
    for i in range(0, detections.shape[2]):
        confidence = detections[0, 0, i, 2]

        # filter out weak detections
        if confidence > 0.3:
            # compute the (x, y)-coordinates of the bounding box for the
            # object
            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
            (startX, startY, endX, endY) = box.astype("int")

            # extract the face ROI
            face = image[startY:endY, startX:endX]

            face = anonymize_face_pixelate(face, blocks=12)

            # store the blurred face in the output image
            image[startY:endY, startX:endX] = face
    os.remove(filename)

    cv2.imwrite(filename, image)
    loadfile = str(filename)
    change_image(loadfile)
    root.update()

    return filename
Пример #6
0
    def setButtons(self):
        self.dpl_img = Image("photo", file="img/deploy.png")
        self.dpl_bt = ttk.Button(self.root,
                                 text="Simulate deployment",
                                 style="nextPrev.TLabel",
                                 image=self.dpl_img,
                                 compound="bottom",
                                 command=self.deployPopup)
        self.dpl_bt.grid(row=0, column=0, columnspan=5, sticky="NESW")
        self.tdoa_img = Image("photo", file="img/TDOA.png")
        self.loc_bt = ttk.Button(self.root,
                                 text="Simulate localization",
                                 style="nextPrev.TLabel",
                                 image=self.tdoa_img,
                                 compound="bottom",
                                 command=self.notAvailable)
        self.loc_bt.grid(row=1, column=0, columnspan=5, sticky="NESW")
        self.dpl = Dpl()

        self.prev_day = ttk.Button(self.root,
                                   text="|◀◀",
                                   style="nextPrev.TLabel",
                                   command=self.previousDay)
        self.prev_day.grid(row=2, column=0, sticky="NESW")
        self.prev_min = ttk.Button(self.root,
                                   text="|◀",
                                   style="nextPrev.TLabel",
                                   command=self.previousMinute)
        self.prev_min.grid(row=2, column=1, sticky="NESW")
        self.play = ttk.Button(self.root,
                               text="▶️",
                               style="play.TLabel",
                               command=self.currentMinute)
        self.play.grid(row=2, column=2, sticky="NESW")
        self.next_min = ttk.Button(self.root,
                                   text="▶️|",
                                   style="nextPrev.TLabel",
                                   command=self.nextMinute)
        self.next_min.grid(row=2, column=3, sticky="NESW")
        self.next_day = ttk.Button(self.root,
                                   text="▶️▶️|",
                                   style="nextPrev.TLabel",
                                   command=self.nextDay)
        self.next_day.grid(row=2, column=4, sticky="NESW")
        self.dt_box = Entry(self.root)
        self.dt_box.configure({"background": self.bg})
        self.dt_box.configure({"foreground": self.fg})
        self.dt_box.grid(row=3, column=0, columnspan=5)
        self.format_dt()
Пример #7
0
    def load_original_image(self):
        response = requests.get(self.image_url,
                                proxies=self.proxies,
                                timeout=TIMEOUT)
        if response.status_code == 404:
            print("image_url response.status_code == 404")
            return

        self.original_image = response.content

        # if DEBUG:
        #     with open(self.original_image_name, 'wb') as f:
        #         f.write(self.original_image)

        self.put_to_cache(self.original_image_name, self.original_image)
        bg_color = 'red'

        self.resized = True

        img = Image.open(io.BytesIO(self.original_image))
        w, h = img.size
        k = MAIN_IMG_WIDTH / w
        img_resized = img.resize((MAIN_IMG_WIDTH, int(h * k)))

        root.after_idle(root.title, f"{root.title()} ({w}x{h})")

        self.main_image_orig = ImageTk.PhotoImage(img)
        self.main_image = ImageTk.PhotoImage(img_resized)

        root.after_idle(self.btn_image.config, {
            'image': self.main_image,
            'background': bg_color
        })
Пример #8
0
    def reconfigure_button(self, http_session, btn, url, img_url):
        global root

        filename = get_filename(img_url)
        dot_pos = filename.rfind('.')
        filename = filename[:dot_pos]
        bg_color = "green"
        image = self.get_from_cache(filename)
        if (image is None) or (len(image) == 0):
            image = download_image(http_session, img_url)
            self.put_to_cache(filename, image)
            bg_color = "red"

        if (image is None) or (len(image) == 0):
            return

        img = Image.open(io.BytesIO(image))
        w, h = img.size
        k = IMG_WIDTH / w
        img_resized = img.resize((IMG_WIDTH, int(h * k)))
        photo_image = ImageTk.PhotoImage(img_resized)
        if photo_image is None:
            return

        root.after_idle(btn.set_values, url,
                        partial(self.load_page_in_thread, url), photo_image,
                        bg_color)
Пример #9
0
 def __init__(self, Sats):
     self.Sats = Sats
     self.sortSats()
     client = MongoClient("localhost", 27017)
     self.db = client["SatConstellation"]
     self.en_db = False
     self.root = Tk()
     self.img = Image("photo", file="img/favicon.png")
     self.root.call('wm', 'iconphoto', self.root._w, self.img)
     self.geometry()
     self.root.title('Pypredict')
     self.setTheme('#404040', 'white', '#303030')
     self.root.protocol("WM_DELETE_WINDOW", quit)
     self.saa = SAA()
     self.updtCnt = 0
     self.dmin = 0
     self.setButtons()
     self.world_map = Map("img/earth_nasa_day.png",
                          "img/earth_nasa_night.png")
     self.plotData()
     self.setCanvas()
     self.setMenu()
     self.data_gen()
     self.changeMainSat(self.Sats[0])
     self.cov_lng = empty(180)
     self.cov_lat = empty(180)
     self.setTableTitles()
     self.setTableContent()
     self.tableRefresher()
     self.setRootBindings()
     self.run()
Пример #10
0
def item_selected(event):
    selected = event.widget.selection()
    for idx in selected:
        nombreTabla = treeview.item(idx)['text']
        nombreBaseDatos = treeview.item(idx)['tags'][0]
    registros = Crud.extractTable(nombreBaseDatos, nombreTabla)
    for i in treeRegs.get_children():
        treeRegs.delete(i)
    if registros:
        columnas = len(registros[0])
        t = []
        for c in range(0, columnas):
            t.append("Col_" + str(c))
        treeRegs["columns"] = t
    treeRegs.column("#0", width=0, minwidth=0, stretch=tk.NO)
    for i in treeRegs["columns"]:
        treeRegs.column(i, width=200, stretch=tk.NO)
        treeRegs.heading(i, text=i.title(), anchor=tk.W)
    mColor = 'par'
    for reg in registros:
        treeRegs.insert("", tk.END, values=reg, tags=(mColor, ))
        if mColor == 'par': mColor = 'impar'
        else: mColor = 'par'
    url = str(pathlib.Path().absolute())
    img = Image.open(url + "\\imagenes\\graficaArboles\\" + nombreTabla +
                     ".png")
    photo = ImageTk.PhotoImage(img)
    lab = Label(image=photo).place(x=310, y=10)
    update_idletasks()
Пример #11
0
 def __init__(self, root, ver):
     self.root = root
     # resize
     self.root.rowconfigure(1, weight=1)
     self.root.columnconfigure(0, weight=1)
     self.root.columnconfigure(1, weight=1)
     self.fo = FileOperation()
     # widgets
     self.panel = (FileList(self, self.fo, 0), FileList(self, self.fo, 1))
     self.bar = Frame(self.root)
     self.bar.grid(row=0, column=0, sticky='we')
     self.menuFile()
     self.menuTag()
     self.menuHelp()
     self.panel[0].grid(row=1, column=0, sticky='nswe')
     self.panel[1].grid(row=1, column=1, sticky='nswe')
     # bind events
     self.root.bind('<F5>', self.copy)
     self.root.bind('<F6>', self.move)
     self.root.bind('<F1>', lambda x: msg.showinfo("Keys", KEYS))
     self.root.bind('<F9>',
                    lambda x: self.fo.execute(self.fo.getRandomFile()))
     self.root.bind('/', self.openSearch)
     self.root.bind('<Control-q>', lambda x: self.root.destroy())
     self.root.bind('=', self.makeEqual)
     # icon, title
     img = Image("photo", file="./manager/img/tm.gif")
     self.root.call('wm', 'iconphoto', self.root._w, img)
     self.root.title('TagManager v.' + ver)
     # evaluate
     self.root.mainloop()
Пример #12
0
    def __init__(self):
        Tk.__init__(self)
        try:
            self.img = Image(
                "photo",
                file=join(dirname(import_module('lucterios.install').__file__),
                          "lucterios.png"))
            self.tk.call('wm', 'iconphoto', self._w, self.img)
        except Exception:
            self.img = None
        self.start_up_app()
        self.has_checked = False
        self.title(ugettext_lazy("Lucterios launcher"))
        self.minsize(475, 260)
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)
        self.running_instance = {}
        self.resizable(True, True)
        self.protocol("WM_DELETE_WINDOW", self.on_closing)

        self.ntbk = ttk.Notebook(self)
        self.ntbk.grid(row=0, column=0, columnspan=1, sticky=(N, S, E, W))

        self.create_instance_panel()
        self.create_module_panel()

        stl = ttk.Style()
        stl.theme_use("default")
        stl.configure("TProgressbar", thickness=5)
        self.progress = ttk.Progressbar(self,
                                        style="TProgressbar",
                                        orient='horizontal',
                                        mode='indeterminate')
        self.progress.grid(row=1, column=0, sticky=(E, W))

        self.btnframe = Frame(self, bd=1)
        self.btnframe.grid(row=2, column=0, columnspan=1)
        Button(self.btnframe,
               text=ugettext_lazy("Refresh"),
               width=20,
               command=self.refresh).grid(row=0,
                                          column=0,
                                          padx=3,
                                          pady=3,
                                          sticky=(N, S))
        self.btnupgrade = Button(self.btnframe,
                                 text=ugettext_lazy("Search upgrade"),
                                 width=20,
                                 command=self.upgrade)
        self.btnupgrade.config(state=DISABLED)
        self.btnupgrade.grid(row=0, column=1, padx=3, pady=3, sticky=(N, S))
        Button(self.btnframe,
               text=ugettext_lazy("Close"),
               width=20,
               command=self.on_closing).grid(row=0,
                                             column=2,
                                             padx=3,
                                             pady=3,
                                             sticky=(N, S))
Пример #13
0
 def show_frame(self):
     frame = cv2.flip(self._engine.canvas, 1)
     cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
     img = Image.fromarray(cv2image)
     imgtk = ImageTk.PhotoImage(image=img)
     self._lmain.imgtk = imgtk
     self._lmain.configure(image=imgtk)
     self._lmain.after(10, self.show_frame)
Пример #14
0
 def create_tab2_test(self):
     """Crea el form de la tab2"""
     img1 = Image("photo", file="./Resources/pinguinoChef.png")
     lbl = ttk.Label(self.tab2, image=img1)
     lbl.image = img1
     lbl.grid(column=0, row=0, sticky='W')
     btn = ttk.Button(self.tab2, image=img1)
     btn.image = img1
     btn.grid(column=0, row=1)
Пример #15
0
def create_window():
    window = turtle.Screen()
    window.title('WhatsApp Statistics')
    favicon = Image("photo", file=(PATH + 'images/favicon.png'))
    turtle._Screen._root.iconphoto(True, favicon)
    window.bgcolor('#040604')
    window.setup(width= 1.0, height= 1.0, startx=0, starty=0)
    window.tracer(0)
    window.addshape(PATH + 'images/logo.gif')
    window.addshape(PATH + 'images/button.gif')
    return window
Пример #16
0
    def analog_drag(self):
        # 刷新一下极验图片
        element = self.driver.find_element_by_xpath(
            '//a[@class="geetest_refresh_1"]')
        element.click()
        time.sleep(1)

        # 保存两张图片
        self.save_img('full.jpg', 'geetest_canvas_fullbg')
        self.save_img('cut.jpg', 'geetest_canvas_bg')
        full_image = Image.open('full.jpg')
        cut_image = Image.open('cut.jpg')
        #
        # 根据两个图片计算距离
        distance = self.get_offset_distance(cut_image, full_image)

        # 开始移动
        self.start_move(distance)

        # 如果出现error
        try:
            WebDriverWait(self.driver, 5, 0.5).until(
                EC.presence_of_element_located(
                    (By.XPATH,
                     '//div[@class="geetest_slider geetest_error"]')))
            print("验证失败")
            return
        except TimeoutException as e:
            pass

# 判断是否验证成功
        try:
            WebDriverWait(self.driver, 10, 0.5).until(
                EC.presence_of_element_located(
                    (By.XPATH,
                     '//div[@class="geetest_slider geetest_success"]')))
        except TimeoutException:
            print("again times")
            self.analog_drag()
        else:
            print("验证成功")
Пример #17
0
def get_prediction(img_path, threshold):
  img = Image.open(img_path) # Load the image
  transform = T.Compose([T.ToTensor()]) # Defing PyTorch Transform
  img = transform(img) # Apply the transform to the image
  pred = model([img]) # Pass the image to the model
  pred_class = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(pred[0]['labels'].numpy())] # Get the Prediction Score
  pred_boxes = [[(i[0], i[1]), (i[2], i[3])] for i in list(pred[0]['boxes'].detach().numpy())] # Bounding boxes
  pred_score = list(pred[0]['scores'].detach().numpy())
  pred_t = [pred_score.index(x) for x in pred_score if x > threshold][-1] # Get list of index with score greater than threshold.
  pred_boxes = pred_boxes[:pred_t+1]
  pred_class = pred_class[:pred_t+1]
  return pred_boxes, pred_class
Пример #18
0
 def configurar_root(self):
     if sys.platform.startswith('win'):
         self.root.iconbitmap(
             'medidor_acustico/resources/icons/mic_icon.ico')
     else:
         mic = Image('photo',
                     file='medidor_acustico/resources/icons/mic_icon.png')
         self.root.tk.call('wm', 'iconphoto', self.root._w, mic)
     self.root.tk_setPalette(background='#831212')
     self.root.resizable(False, False)
     self.root.protocol('WM_DELETE_WINDOW',
                        self.controller.on_cerrar_ventana)
Пример #19
0
def save_picture(form_picture):
    random_hex = secrets.token_hex()
    _, f_ext = os.path.splitext(form_picture.filename)
    picture_fn = random_hex + f_ext
    picture_path = os.path.join(app.root_path, 'static/profile_pics',
                                picture_fn)
    output_size = (125, 125)
    i = Image.open(form_picture)
    i.thumbnail(output_size)
    form_picture.save(picture_path)

    return picture_fn
Пример #20
0
def Soumettre(pMotChoisit, pMotEnCours) :
    global nbrTentatives
    nbrTentatives = 0
    for i in range(len(pMotChoisit)) :
        if pMotChoisit[i] == Reponse.get() :
            pMotEnCours = pMotEnCours.split()[0:len(pMotChoisit)]
            pMotEnCours[i] = Reponse.get()
            pMotEnCours = ' '.join(pMotEnCours)
        else :
            nbrTentatives += 1
            nbrTentatives = Image(nbrTentatives)
    return pMotEnCours, nbrTentatives
Пример #21
0
    def main(self):
        #Enabling the foreign key support
        self.QUERY = "PRAGMA foreign_keys = ON"
        self.cursor.execute(self.QUERY)
        self.conn.commit()

        #Setting the icon of the file
        image = ImageTk.PhotoImage(Image.open('./logo.ico'))
        self.root.iconphoto(False, image)

        self.loginFrame()

        self.root.mainloop()
Пример #22
0
    def load_image(self):
        try:
            with opener.open(self.img_url) as f:
                raw_data = f.read()
                content = io.BytesIO(raw_data)
                img = Image.open(content)
                self.model_image = ImageTk.PhotoImage(img)
                self.image_label.config(image=self.model_image)
        except BaseException as e:
            logger.exception(e)

        self.master.update_idletasks()
        self.master.after(DELAY, self.load_image)
Пример #23
0
def get_result(image_path):

    new_model = load_model("covid_model.h5")

    new_model.summary()
    img_width, img_height = 224, 224
    img = image.load_img(image_path, target_size=(img_width, img_height))
    x = image.img_to_array(img)
    img = np.expand_dims(x, axis=0)

    pred = new_model.predict(img)
    print(pred)  # норм тут
    print(np.argmax(pred, axis=1))
    prediction = np.argmax(pred, axis=1)

    im = Image.open(image_path)
    resized = im.resize((350, 400), Image.ANTIALIAS)
    resized.save("result.jpg")
    print_on_image = ''
    if prediction == 0:
        print_on_image = 'Covid-19'
    else:
        print_on_image = 'Non_Covid-19'

    image_cv = cv2.imread("result.jpg")
    output = image_cv.copy()
    cv2.putText(output, print_on_image, (10, 390), cv2.FONT_HERSHEY_SIMPLEX, 1,
                (0, 0, 255), 3)
    cv2.imwrite("result_name.jpg", output)

    #gif1 = PhotoImage(file="result_name.gif")
    #canvas.create_image(244, 244, image=gif1, anchor=NW)

    new_image = Image.open("result_name.jpg")
    tkimage = ImageTk.PhotoImage(new_image)

    imag_e.config(image=tkimage)
    imag_e.image = tkimage
    imag_e.pack(side="bottom", fill="both", expand="yes")
Пример #24
0
    def fetch_image(self):
        global root

        try:
            response = self.http_session.get(self.img_url, timeout=TIMEOUT)
            img = Image.open(io.BytesIO(response.content))
            w, h = img.size
            k = 200 / w
            img_resized = img.resize((200, int(h * k)))
            root.after_idle(self.update_image, img_resized)
        except BaseException as error:
            root.after_idle(self.set_undefined_state)
            print("Exception URL: " + self.img_url)
            print(error)
            traceback.print_exc()
Пример #25
0
def redOrBlack (im):
    newimdata = []
    redcolor = (0, 0, 0)
    redcolor1 = (105, 105, 105)

    blackcolor = (255,0,0)
    for color in im.getdata():
        if color >= redcolor or color <= redcolor1:
            newimdata.append( (0,125,0) )
        else:
            newimdata.append( color)
    newim = Image.new(im.mode,im.size)
    newim.putdata(newimdata)
    return newim

    redOrBlack(im).save("Faces/fotso.png")
#img.save("Faces/foto.png")
Пример #26
0
def save():
    # global image_number
    img_pkl_number = pickle.load(open("save.p", "rb"))
    filename = f'img_{img_pkl_number}.bmp'
    # save the file
    image1.save(filename)
    # resize the image based on the width (REQUIRED TO BE SQUARE)
    basewidth = 28
    img = Image.open(filename)
    wpercent = (basewidth / float(img.size[0]))
    hsize = int((float(img.size[1]) * float(wpercent)))
    img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
    img.save(filename)
    img_pkl_number += 1
    pickle.dump(img_pkl_number, open("save.p", "wb"))
    # LINE ONLY TO KEEP IMAGES AT 0
    restart()
Пример #27
0
def getImageWithID(path):
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    #   print(imagePaths) #in duong dan anh
    faces = []
    IDs = []
    # chuyen doi anh thanh ma tran
    for imagePath in imagePaths:
        faceImg = Image.open(imagePath).convert('L')
        faceNp = np.array(faceImg, 'uint8')  #lay du lieu anh
        print(faceNp)  #in anh ve dang array
        get_Id = int(imagePath.split('.')[1])  #lay du lieu ID
        print("\ngetid=", get_Id)
        faces.append(faceNp)
        IDs.append(get_Id)
        cv2.imshow('trainning', faceNp)
        cv2.waitKey(10)
    return faces, IDs
Пример #28
0
def version_icon(request, project_id, version_integer):
    if int(version_integer) < 0:
        return None
    project = Project.objects.get(pk=project_id)
    versions = project.application.versions
    version = versions.filter(version_integer=version_integer)[0]
    img_uri = config.APPS_FOLDER + str(project.pk) + "/" + str(version.version_integer) + "/" + "icon.png"
    try:
        with open(img_uri, "rb") as f:
            content_length = os.path.getsize(img_uri)
            response = HttpResponse(f.read(), content_type="image/jpeg")
            response['Content-Length'] = content_length
            return response
    except IOError:
        red = Image.new('RGBA', (1, 1), (255, 0, 0, 0))
        response = HttpResponse(mimetype="image/jpeg")
        red.save(response, "JPEG")
        return response
Пример #29
0
 def form_details(self, name):
     produc = self.model.read_product(name)
     self.form_new_product()
     self.name.set(produc['name'])
     self.detail.set(produc['description'])
     self.cost.set(produc['cost'])
     self.tam.set(produc['size'])
     self.stock.set(produc['stock'])
     self.btn_save.configure(state='disabled')
     self.btn_save.grid_forget()
     self.btn_close = ttk.Button(self.topl,
                                 text=self.i18n.close,
                                 command=lambda: self.topl.destroy())
     lblimg = Image('photo',
                    file='/home/jintan/PycharmProjects/El_Panque/pin.png')
     lbl_img = ttk.Label(self.topl, image=lblimg)
     lbl_img.image = lblimg
     lbl_img.grid(column=2, row=0, rowspan=7)
     self.btn_close.grid(column=2, row=7, sticky=tk.SE)
Пример #30
0
 def cv2ImgAddText(self,
                   img,
                   text,
                   left,
                   top,
                   textColor=(0, 255, 0),
                   textSize=20):
     if (isinstance(img, numpy.ndarray)):  # 判断是否OpenCV图片类型
         img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
     # 创建一个可以在给定图像上绘图的对象
     draw = ImageDraw.Draw(img)
     # 字体的格式
     fontStyle = ImageFont.truetype("font/simsun.ttc",
                                    textSize,
                                    encoding="utf-8")
     # 绘制文本
     draw.text((left, top), text, textColor, font=fontStyle)
     # 转换回OpenCV格式
     return cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)