Пример #1
0
def resize(imgFile):
	im1 = Image.open(imgFile)
	width, height = im1.size
	ratio = (width*100/height)
	#if ratio < 60 or ratio > 150:
	#	print imgFile
	#im1.close()
	print imgFile, "(original):", width, "x", height
	im2 = im1.resize((150,150), Image.ANTIALIAS)
	im2.save(imgFile)
	width, height = im2.size
	print imgFile, "(new):", width, "x", height
def create_image(filename,
                 size=(1280, 720),
                 message="Text",
                 bg_color=random_color(),
                 number=-1,
                 text_color="white"):
    """Creates a image .png file with the text"""

    # create an image that we can draw on
    img = Image.new("RGB", size, bg_color)
    draw = ImageDraw.Draw(img)

    # load font for the main text (message)
    font_main_text = ImageFont.truetype("FiraCode-Regular.ttf", 50)

    # get position so that the message is located in the middle of the image
    width_2, height_2 = draw.textsize(message, font=font_main_text)
    position_text = ((size[0] - width_2) / 2, (size[1] - height_2) / 2)

    # draw the text on the image
    draw.text(position_text, message, fill=text_color, font=font_main_text)

    # if wanted (number!=-1) add a sub text to the image
    if number != -1:

        # load font for the sub text
        font_sub_text = ImageFont.truetype("FiraCode-Regular.ttf", 30)

        # determine position of the sub text in the middle but slightly down
        width_2, height_2 = draw.textsize(">> Demo file #" + str(number),
                                          font=font_sub_text)
        position_text = ((size[0] - width_2) / 2,
                         (size[1] - height_2) / 2 + 100)

        # draw the sub text on the image
        draw.text(position_text,
                  ">> Demo file #" + str(number),
                  fill=text_color,
                  font=font_sub_text)

    # save draw object as a image
    draw = ImageDraw.Draw(img)
    img.save(filename)
def brightness():
    global panel
    x = openfn()
    im = Image.open(x)
    im3 = ImageEnhance.Brightness(im)
    im2 = im3.enhance(2.0)
    img = im2.resize((1000, 800), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(img)
    panel = Label(root, image=img)
    panel.image = img
    panel.pack()

    #panel.image = NONE
    def saveb():
        MsgBox = tk.messagebox.askquestion('SAVE',
                                           'do you want to save the img',
                                           icon='warning')
        if MsgBox == 'yes':
            im3.enhance(2.0).save("brightness.jpg")

    threading.Timer(5.0, saveb).start()
def blur():
    global panel
    x = openfn()
    img = Image.open(x)
    im = img.filter(ImageFilter.BLUR)
    img = im.resize((1250, 900), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(img)

    panel = Label(root, image=img)
    panel.image = img
    #panel.image = NONE
    panel.pack(side="top", fill="both", expand="NO")

    def saveb():
        MsgBox = tk.messagebox.askquestion('SAVE',
                                           'do you want to save the img',
                                           icon='warning')
        if MsgBox == 'yes':
            im.save('blur.jpg')

    threading.Timer(5.0, saveb).start()
def rotate():
    global panel
    x = openfn()
    image_obj = Image.open(x)
    rotated_image = image_obj.rotate(90)
    img = rotated_image.resize((1250, 900), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(img)
    panel = Label(root, image=img)
    panel.image = img
    panel.pack(side="top", fill="both", expand="NO")

    #rotated_image.save(saved_location)
    #rotated_image.show()
    def saveb():
        MsgBox = tk.messagebox.askquestion('SAVE',
                                           'do you want to save the img',
                                           icon='warning')
        if MsgBox == 'yes':
            rotated_image.save('rotate.JPEG')

    threading.Timer(5.0, saveb).start()
def sharpen():
    global panel
    x = openfn()
    im = Image.open(x)
    im_sharp = im.filter(ImageFilter.SHARPEN)
    img = im_sharp.resize((1250, 900), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(img)
    panel = Label(root, image=img)
    panel.image = img
    panel.pack(side="top", fill="both", expand="NO")

    #im_sharp.save('image_sharpened.jpg', 'JPEG')
    #im_sharp.show()
    def saveb():
        MsgBox = tk.messagebox.askquestion('SAVE',
                                           'do you want to save the img',
                                           icon='warning')
        if MsgBox == 'yes':
            im_sharp.save('sharpen.jpg')

    threading.Timer(5.0, saveb).start()
Пример #7
0
def getImagesAndLabels(path):
    #get the path of all the files in the folder
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    #create empth face list
    faceSamples = []
    #create empty ID list
    Ids = []
    #now looping through all the image paths and loading the Ids and the images
    for imagePath in imagePaths:
        #loading the image and converting it to gray scale
        pilImage = Image.open(imagePath).convert('L')
        #Now we are converting the PIL image into numpy array
        imageNp = np.array(pilImage, 'uint8')
        #getting the Id from the image
        Id = int(os.path.split(imagePath)[-1].split(".")[1])
        # extract the face from the training image sample
        faces = detector.detectMultiScale(imageNp)
        #If a face is there then append that in the list as well as Id of it
        for (x, y, w, h) in faces:
            faceSamples.append(imageNp[y:y + h, x:x + w])
            Ids.append(Id)
    return faceSamples, Ids
Пример #8
0
def getIImage(b64_img):
    valid_types = ('png','jpg','jpeg')
    imgBytes = base64.decodebytes(b64_img.encode('UTF-8'))
    imgType = imghdr.what(None, imgBytes)
    if imgType not in valid_types: # we should convert it!
        imgSI = BytesIO(imgBytes)
        imgSO = BytesIO()
        img = Image.open(imgSI)
        if img.format.lower() in valid_types:
            imgB64 = b64_img
            imgType = img.format
        else:
            img.save(imgSO, 'png')
            imgSO.seek(0)
            imgB64 = base64.encodebytes(imgSO.read()).decode('UTF-8').replace("\n", "")
            imgType = 'png'
        img.close()
        imgSO.close()
        imgSI.close()
    else:
        imgB64 = b64_img
    
    return imgB64, imgType
    def __getitem__(self, item):

        image = Image.open(self.image_paths[item])
        image = image.convert('RGB')

        targets = self.targets[item]

        if self.resize is not None:
            image = image.resize((self.resize[1], self.resize[0]),
                                 resample=Image.BILINEAR)

        image = np.array(image)

        if self.augmentations is not None:
            augmented = self.augmentations(image=image)
            image = augmented['image']

        image = np.transpose(image, (2, 0, 1)).astype(np.float64)

        return {
            'image': torch.tensor(image, dtype=torch.float),
            'targets': torch.tensor(targets, dtype=torch.long)
        }
Пример #10
0
def getImagesWithID(path):
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    #print (imagePaths)

    #getImagesWithID(path)

    faces = []
    IDs = []
    for imagePath in imagePaths:
        faceImg = Image.open(imagePath).convert('L')
        # this is pil image so we need to convert it into numpy array so that open cv can work with it
        faceNp = np.array(faceImg, 'uint8')

        #now we want face ids
        ID = int(os.path.split(imagePath)[-1].split('.')[1])
        #now we have id and images now we can directly store it to into the faces and ids.
        faces.append(faceNp)
        IDs.append(ID)
        cv2.imshow("training",
                   faceNp)  #to show which images  that are captured.
        cv2.waitKey(70)

    return np.array(IDs), faces
Пример #11
0
def load_images(file):
    """
    Function loads black and white image and convert it to CIE LAB

    Parameters
    ----------
    file : str
        Path to image file

    Returns
    -------
    ndarray
        3D array with image
    """

    try:
        img = Image.open(file)
    except (OSError, ValueError, IOError, ZeroDivisionError) as e:
        print("Can not open file", file, "Error: ", e)
        return None
    img = img.convert(mode="RGB")  # ensure that image rgb
    rgb = np.array(img)

    return color.rgb2lab(rgb)
Пример #12
0
    def parse(self, label_path, img_path, img_type=".png"):
        try:

            (dir_path, dir_names,
             filenames) = next(os.walk(os.path.abspath(label_path)))

            data = {}

            progress_length = len(filenames)
            progress_cnt = 0
            printProgressBar(0,
                             progress_length,
                             prefix='\nYOLO Parsing:'.ljust(15),
                             suffix='Complete',
                             length=40)

            for filename in filenames:

                txt = open(os.path.join(dir_path, filename), "r")

                filename = filename.split(".")[0]

                img = Image.open(
                    os.path.join(img_path, "".join([filename, img_type])))
                img_width = str(img.size[0])
                img_height = str(img.size[1])
                img_depth = 3

                size = {
                    "width": img_width,
                    "height": img_height,
                    "depth": img_depth
                }

                obj = {}
                obj_cnt = 0

                for line in txt:
                    elements = line.split(" ")
                    name_id = elements[0]

                    xminAddxmax = float(elements[1]) * (2.0 * float(img_width))
                    yminAddymax = float(
                        elements[2]) * (2.0 * float(img_height))

                    w = float(elements[3]) * float(img_width)
                    h = float(elements[4]) * float(img_height)

                    xmin = (xminAddxmax - w) / 2
                    ymin = (yminAddymax - h) / 2
                    xmax = xmin + w
                    ymax = ymin + h

                    bndbox = {
                        "xmin": float(xmin),
                        "ymin": float(ymin),
                        "xmax": float(xmax),
                        "ymax": float(ymax)
                    }

                    obj_info = {"name": name_id, "bndbox": bndbox}

                    obj[str(obj_cnt)] = obj_info
                    obj_cnt += 1

                obj["num_obj"] = obj_cnt

                data[filename] = {"size": size, "objects": obj}

                printProgressBar(progress_cnt + 1,
                                 progress_length,
                                 prefix='YOLO Parsing:'.ljust(15),
                                 suffix='Complete',
                                 length=40)
                progress_cnt += 1

            return True, data

        except Exception as e:

            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]

            msg = "ERROR : {}, moreInfo : {}\t{}\t{}".format(
                e, exc_type, fname, exc_tb.tb_lineno)

            return False, msg
Пример #13
0
    def parse(label_path, img_path, img_type=".png"):

        try:
            with open("box_groups.txt", "w") as bboxGroups:
                (dir_path, dir_names,
                 filenames) = next(os.walk(os.path.abspath(label_path)))

                data = {}

                progress_length = len(filenames)
                progress_cnt = 0
                printProgressBar(0,
                                 progress_length,
                                 prefix='\nKITTI Parsing:'.ljust(15),
                                 suffix='Complete',
                                 length=40)

                for filename in filenames:

                    txt = open(os.path.join(dir_path, filename), "r")

                    filename = filename.split(".")[0]

                    img = Image.open(
                        os.path.join(img_path, "".join([filename, img_type])))
                    img_width = str(img.size[0])
                    img_height = str(img.size[1])
                    img_depth = 3

                    size = {
                        "width": img_width,
                        "height": img_height,
                        "depth": img_depth
                    }

                    obj = {}
                    obj_cnt = 0

                    for line in txt:
                        elements = line.split(" ")
                        name = elements[0]
                        if name == "DontCare":
                            continue

                        xmin = elements[4]
                        ymin = elements[5]
                        xmax = elements[6]
                        ymax = elements[7]

                        bndbox = {
                            "xmin": float(xmin),
                            "ymin": float(ymin),
                            "xmax": float(xmax),
                            "ymax": float(ymax)
                        }

                        bboxGroups.write("{} {} {} {}\n".format(
                            float(xmin), float(ymin),
                            float(xmax) - float(xmin),
                            float(ymax) - float(ymin)))

                        obj_info = {"name": name, "bndbox": bndbox}

                        obj[str(obj_cnt)] = obj_info
                        obj_cnt += 1

                    obj["num_obj"] = obj_cnt

                    data[filename] = {"size": size, "objects": obj}

                    printProgressBar(progress_cnt + 1,
                                     progress_length,
                                     prefix='KITTI Parsing:'.ljust(15),
                                     suffix='Complete',
                                     length=40)
                    progress_cnt += 1

                return True, data

        except Exception as e:

            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]

            msg = "ERROR : {}, moreInfo : {}\t{}\t{}".format(
                e, exc_type, fname, exc_tb.tb_lineno)

            return False, msg
Пример #14
0
    def parse(csv_path, img_path):

        try:

            raw_f = open(csv_path, 'r', encoding='utf-8')
            csv_f = csv.reader(raw_f)

            progress_length = sum(1 for row in csv_f)
            raw_f.seek(0)

            progress_cnt = 0
            printProgressBar(0,
                             progress_length,
                             prefix='\nUDACITY Parsing:'.ljust(15),
                             suffix='Complete',
                             length=40)

            data = {}

            for line in csv_f:

                raw_line = line[0].split(" ")
                raw_line_length = len(raw_line)

                filename = raw_line[0].split(".")[0]
                xmin = float(raw_line[1])
                ymin = float(raw_line[2])
                xmax = float(raw_line[3])
                ymax = float(raw_line[4])
                cls = raw_line[6].split('"')[1]

                if raw_line_length is 8:
                    state = raw_line[7].split('"')[1]
                    cls = cls + state

                img = Image.open(
                    os.path.join(img_path, "".join([filename, ".jpg"])))
                img_width = str(img.size[0])
                img_height = str(img.size[1])
                img_depth = 3

                size = {
                    "width": img_width,
                    "height": img_height,
                    "depth": img_depth
                }

                bndbox = {
                    "xmin": xmin,
                    "ymin": ymin,
                    "xmax": xmax,
                    "ymax": ymax
                }

                obj_info = {"name": cls, "bndbox": bndbox}

                if filename in data:
                    obj_idx = str(int(data[filename]["objects"]["num_obj"]))
                    data[filename]["objects"][str(obj_idx)] = obj_info
                    data[filename]["objects"]["num_obj"] = int(obj_idx) + 1
                elif filename not in data:
                    obj = {"num_obj": "1", "0": obj_info}

                    data[filename] = {"size": size, "objects": obj}

                printProgressBar(progress_cnt + 1,
                                 progress_length,
                                 prefix='UDACITY Parsing:'.ljust(15),
                                 suffix='Complete',
                                 length=40)
                progress_cnt += 1

            return True, data

        except Exception as e:

            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]

            msg = "ERROR : {}, moreInfo : {}\t{}\t{}".format(
                e, exc_type, fname, exc_tb.tb_lineno)

            return False, msg
Пример #15
0
from selenium.webdriver import Chrome, ChromeOptions
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import ActionChains
option = ChromeOptions()
# option.add_experimental_option('excludeSwitches',['enable-automation'])
chrome_option = Options()
# chrome_option.add_argument('--headless')
# chrome_option.add_argument('--dosable-gpu')
es = Chrome(options=option, chrome_options=chrome_option)
es.get('https://www.baidu.com/')
sleep(5)
es.save_screenshot('./day05/1.png')
img = es.find_element_by_xpath('//div[@id="lg"]/img')
sleep(3)
location = img.location
size = img.size
rangle = (int(location['x']), int(location['y']),
          int(location['x'] + size['width']),
          int(location['y'] + size['height']))
print(rangle)
i = Image.open('./day05/1.png')
frame = i.crop(rangle)
frame.save('./day05/frame.png')
# 构建数据流对图片进行点击操作
action = ActionChains(es)
# move_to_element_with_offset()  第一个参数是作为目标的图片,第二个参数和第三个参数分别为横向便宜和纵向偏移
# click() 方法,进行点击
# perform()  将设定好的数据流立即执行
action.move_to_element_with_offset(img, 5, 5).click().perform()
sleep(3)
es.quit()
Пример #16
0
    "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")


def get_char(r, g, b, alpha=256):
    if alpha == 0:
        return ' '
    length = len(ascii_char)
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)

    unit = (256.0 + 1) / length
    return ascii_char[int(gray / unit)]


if __name__ == '__main__':

    im = Image.open(IMG)
    im = im.resize((WIDTH, HEIGHT), Image.NEAREST)

    txt = ""

    for i in range(HEIGHT):
        for j in range(WIDTH):
            txt += get_char(*im.getpixe((j, i)))
        txt += '\n'

    print(txt)

    if OUTPUT:
        with open(OUTPUT, 'w') as f:
            f.write(txt)
    else:
Пример #17
0
def open_file_as_pil_image(source_file):
    """Return a new Image object from source file."""
    return Image.open(source_file)
Пример #18
0
def CenterExtend(im, width=400, height=88, radius=20):
    x1 = np.full((height+radius+radius, width+radius+radius), 255, dtype='uint8')
    x2 = np.asarray(im.convert('L'))
    x1[radius:radius+height,radius:radius+width] = x2
    return Image.fromarray(x1, 'L')
Пример #19
0
    def __init__(self, master=None):
        super().__init__(master, padx=12, pady=3)

        if getattr(sys, 'frozen', False):
            self.baseDir = os.path.dirname(sys.executable)
        else:
            self.baseDir = os.path.dirname(os.path.realpath(__file__))

        self.loadConfig()

        self.master = master
        self.queue = queue.initQueue()

        self.grid()

        rowIndex = 0
        self.logoImage = ImageTk.PhotoImage(Image.open('logo.png'))

        self.logoLabel = tk.Label(self, image=self.logoImage)
        self.logoLabel.grid(row=rowIndex, column=0, columnspan=5)

        rowIndex += 1

        self.deckNameLabel = tk.Label(self, text='Deckname')
        self.deckNameLabel.grid(row=rowIndex, column=0, sticky=tk.W)

        self.deckNameEntry = tk.Entry(self, width=60)
        self.deckNameEntry.grid(row=rowIndex,
                                column=1,
                                columnspan=3,
                                stick=tk.W)
        self.deckNameEntry.insert(0, 'Deck')

        rowIndex += 1
        self.inputLabel = tk.Label(self, text='File or URL')
        self.inputLabel.grid(row=rowIndex, column=0, sticky=tk.W)

        self.inputEntry = tk.Entry(self, width=60)
        self.inputEntry.grid(row=rowIndex, column=1, columnspan=3, sticky=tk.W)

        self.inputButton = tk.Button(self,
                                     text='Browse',
                                     command=self.openFile)
        self.inputButton.grid(row=rowIndex, column=4, sticky=tk.E)

        rowIndex += 1
        self.outputLabel = tk.Label(self, text='Output folder (optional)')
        self.outputLabel.grid(row=rowIndex, column=0, sticky=tk.W)

        self.outputEntry = tk.Entry(self, width=60)
        self.outputEntry.grid(row=rowIndex,
                              column=1,
                              columnspan=3,
                              sticky=tk.W)
        self.outputEntry.insert(0, self.config['outputFolder'])

        self.outputButton = tk.Button(self,
                                      text='Browse',
                                      command=self.openFolder)
        self.outputButton.grid(row=rowIndex, column=4, sticky=tk.E)

        rowIndex += 1
        self.imgurLabel = tk.Label(self, text='ImgurID (optional)')
        self.imgurLabel.grid(row=rowIndex, column=0, sticky=tk.W)

        self.imgurEntry = tk.Entry(self, width=60)
        self.imgurEntry.grid(row=rowIndex, column=1, columnspan=3, sticky=tk.W)
        if self.config['imgurId']:
            self.imgurEntry.insert(0, self.config['imgurId'])
        self.imgurEntry.config(state='disabled')

        rowIndex += 1
        self.dropboxLabel = tk.Label(self, text='Dropbox Token(optional)')
        self.dropboxLabel.grid(row=rowIndex, column=0, sticky=tk.W)

        self.dropboxEntry = tk.Entry(self, width=60)
        self.dropboxEntry.grid(row=rowIndex,
                               column=1,
                               columnspan=3,
                               sticky=tk.W)
        if self.config['dropboxToken']:
            self.dropboxEntry.insert(0, self.config['dropboxToken'])
        self.dropboxEntry.config(state='disabled')

        rowIndex += 1
        self.basicsLabel = tk.Label(self, text='Basic lands')
        self.basicsLabel.grid(row=rowIndex, column=0, sticky=tk.W)

        basicsOptions = ('guru', 'unstable', 'alpha', 'core', 'guay')
        self.basicsVar = tk.StringVar()
        self.basicsVar.set(self.config['basicSet'])
        self.basicsMenu = tk.OptionMenu(self, self.basicsVar, *basicsOptions)
        self.basicsMenu.grid(row=rowIndex, column=1, columnspan=2, sticky=tk.W)

        rowIndex += 1
        self.hiresVar = tk.IntVar()
        self.hiresVar.set(int(self.config['hires']))
        self.hiresCheckbutton = tk.Checkbutton(self,
                                               text='High Resolution',
                                               variable=self.hiresVar)
        self.hiresCheckbutton.grid(row=rowIndex, column=0, sticky=tk.W)
        self.hiresVar.trace('w', self.hiresVarCallback)

        self.reprintsVar = tk.IntVar()
        self.reprintsVar.set(int(self.config['reprints']))
        self.reprintsCheckbutton = tk.Checkbutton(self,
                                                  text='Reprints',
                                                  variable=self.reprintsVar)
        self.reprintsCheckbutton.grid(row=rowIndex, column=1, sticky=tk.W)

        self.nocacheVar = tk.IntVar()
        self.nocacheVar.set(int(self.config['nocache']))
        self.nocacheCheckbutton = tk.Checkbutton(self,
                                                 text='No cache',
                                                 variable=self.nocacheVar)
        self.nocacheCheckbutton.grid(row=rowIndex, column=2, sticky=tk.W)

        self.imgurVar = tk.IntVar()
        self.imgurVar.set(int(self.config['imgur']))
        self.imgurCheckbutton = tk.Checkbutton(self,
                                               text='Imgur Upload',
                                               variable=self.imgurVar)
        self.imgurCheckbutton.grid(row=rowIndex, column=3, sticky=tk.W)
        self.imgurVar.trace('w', self.imgurVarCallback)
        self.updateImgurEntry()

        self.dropboxVar = tk.IntVar()
        self.dropboxVar.set(int(self.config['dropbox']))
        self.dropboxCheckbutton = tk.Checkbutton(self,
                                                 text='Dropbox Upload',
                                                 variable=self.dropboxVar)
        self.dropboxCheckbutton.grid(row=rowIndex, column=4, sticky=tk.W)
        self.dropboxVar.trace('w', self.dropboxVarCallback)
        self.updateDropboxEntry()

        rowIndex += 1
        self.progressLabel = tk.Label(self, text='Ready')
        self.progressLabel.grid(row=rowIndex,
                                column=0,
                                columnspan=4,
                                sticky=tk.W)

        self.generateButton = tk.Button(self,
                                        text='Generate',
                                        command=self.generate)
        self.generateButton.grid(row=rowIndex, column=4, sticky=tk.E)

        self.processQueue()
Пример #20
0
    for file in files:
        if file.endswith("png") or file.endswith("jpg"):
            path = os.path.join(root, file)
            label = os.path.basename(os.path.dirname(path)).replace(
                " ", "-").lower()
            #print(label, path)

            if not label in label_ids:
                label_ids[label] = current_id
                current_id += 1

            id_ = label_ids[label]
            #print(label_ids)
            #y_labels.append(label)
            #x_train.append(path)  #Verify this image, turn it into numpy array, GRAY
            pil_image = Image.open(path).convert("L")  #grayscale
            size = (550, 550)
            final_image = pil_image.resize(size, Image.ANTIALIAS)

            image_array = np.array(final_image, "uint8")
            #print(image_array)

            faces = face_cascade.detectMultiScale(image_array,
                                                  scaleFactor=1.5,
                                                  minNeighbors=5)

            for (x, y, w, h) in faces:
                roi = image_array[y:y + h, x:x + w]
                x_train.append(roi)
                y_labels.append(id_)
Пример #21
0
def open_file_as_pil_image(source_file):
    """Return a new Image object from source file."""
    return Image.open(source_file)
Пример #22
0
def create_empty_pil_image(pil_image):
    """Create an empty PIL Image."""
    return Image.new('RGB', (pil_image.size[0], pil_image.size[1]))
Пример #23
0
# start button created
startb = Button(window1,
                text="START",
                command=start_fun,
                font=("Arial", 25),
                bg="orange",
                fg="blue",
                borderwidth=3,
                relief="raised")
startb.place(x=130, y=590)

# image on the main window
path = "Images/front.png"
# Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img1 = ImageTk.PhotoImage(Image.open(path))
# The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window1, image=img1)
panel.place(x=320, y=200)


# function created for exiting
def exit_win():
    if mbox.askokcancel("Exit", "Do you want to exit?"):
        window1.destroy()


# exit button created
exitb = Button(window1,
               text="EXIT",
               command=exit_win,
Пример #24
0
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 14 16:07:12 2020

@author: Sourav
"""#Import required Image library
 
import cv2 
import os
from pil import Image,ImageFilter

im = Image.open('G:\chk2.jpg')

#im.show()
cropped = im.crop((472,147,703,241))
gaussImage = cropped.filter(ImageFilter.GaussianBlur(20))
im.paste(gaussImage,(472,147,703,241))

im.save('G:\masked1.jpg')

    
# Reading an image in default mode 
image = cv2.imread('G:\masked1.jpg') 
directory = r'G:\Chequemasking' 
os.chdir(directory)
print(os.listdir(directory))
# font 
font = cv2.FONT_HERSHEY_PLAIN
org = (472,220) 
  
# fontScale 
Пример #25
0
# Tensorflow Hub shall give us pre trained model URLs
classifierUrl = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4"
imageUrl = "https://storage.googleapis.com/download.tensorflow.org/example_images/grace_hopper.jpg"
labelsUrl = "https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt"

IMAGE_SHAPE = (224, 224)
INPUT_IMAGE_SHAPE = (224, 224, 3)
# Deep Learning model from TF HUB
model = tf.keras.Sequential(
    [hub.KerasLayer(classifierUrl, input_shape=INPUT_IMAGE_SHAPE)])
print(model.summary())

# read the Image from URL
graceHopperImage = tf.keras.utils.get_file('image.jpg', imageUrl)
graceHopperImage = Image.open(graceHopperImage).resize(IMAGE_SHAPE)
print(graceHopperImage)

# Image preprocessing for deep learming model Input

graceHopperImage = np.array(graceHopperImage) / 255.0
print(graceHopperImage.shape)

# read the Labels and store them in a list
labelPath = tf.keras.utils.get_file("ImageNetLabels.txt", labelsUrl)
labels = np.array(open(labelPath).read().splitlines())
print(labels)

# Lets Use the Model for making predictions
result = model.predict(graceHopperImage[np.newaxis, :])
predictedClassLabelIdx = np.argmax(result[0], axis=-1)
y_labels = []
x_train = []

for root, dirs, files in os.walk(image_dir):
    for file in files:
        if file.endswith("jpg") or file.endswith("JPG"):
            path = os.path.join(root, file)
            label = os.path.basename(root).replace(" ", "-").lower()
            #print(label, path)
            if not label in label_ids:
                label_ids[label] = current_id
            current_id += 1
            id_ = label_ids[label]
            #print(label_ids)

            pil_image = Image.open(path).convert("L")
            size = (550, 550)
            final_image = pil_image.resize(size, Image.ANTIALIAS)

            image_array = np.array(pil_image, "uint8")
            #print(image_array)
            faces = face_casecade.detectMultiScale(image_array,
                                                   scaleFactor=1.5,
                                                   minNeighbors=5)
            for (x, y, w, h) in faces:
                #print(x, y, w, h)
                roi = image_array[y:y + h, x:x + w]
                x_train.append(roi)
                y_labels.append(id_)

#print(y_labels)
Пример #27
0
def main():
    pp = pprint.PrettyPrinter(indent=4)

    img_path = args.img_path
    label_path = args.label_path
    img_type = args.img_type
    datasets = args.datasets
    cls_list = args.cls_list_file

    result = None
    data = None

    if datasets == "COCO":
        coco = COCO()
        result, data = coco.parse(label_path)
    elif datasets == "VOC":
        voc = VOC()
        result, data = voc.parse(label_path)
    elif datasets == "UDACITY":
        udacity = UDACITY()
        result, data = udacity.parse(label_path, img_path)
    elif datasets == "KITTI":
        kitti = KITTI()
        result, data = kitti.parse(label_path, img_path, img_type=img_type)
    elif datasets == "YOLO":
        yolo = YOLO(os.path.abspath(cls_list))
        result, data = yolo.parse(label_path, img_path, img_type=img_type)

    if result is True:
        for key in data:

            filepath = "".join([img_path, key, img_type])

            im = Image.open(filepath)

            draw = ImageDraw.Draw(im)
            print("data['{}']: ".format(key), end="")
            pp.pprint(data[key])
            print("num_object : {}".format(data[key]["objects"]["num_obj"]))
            for idx in range(0, int(data[key]["objects"]["num_obj"])):
                print("idx {}, name : {}, bndbox :{}".format(
                    idx, data[key]["objects"][str(idx)]["name"],
                    data[key]["objects"][str(idx)]["bndbox"]))

                x0 = data[key]["objects"][str(idx)]["bndbox"]["xmin"]
                y0 = data[key]["objects"][str(idx)]["bndbox"]["ymin"]
                x1 = data[key]["objects"][str(idx)]["bndbox"]["xmax"]
                y1 = data[key]["objects"][str(idx)]["bndbox"]["ymax"]

                draw.rectangle(((x0, y0), (x1, y1)), outline='#00ff88')
                draw.text((x0, y0), data[key]["objects"][str(idx)]["name"])

            del draw
            print(
                "===============================================================================================\n\n"
            )
            plt.imshow(im)
            plt.show()
            plt.clf()
            im.close()

    else:
        print("return value : {}, msg : {}, args: {}".format(
            result, data, args))
Пример #28
0
def create_empty_pil_image(pil_image):
    """Create an empty PIL Image."""
    return Image.new('RGB', (pil_image.size[0], pil_image.size[1]))
Пример #29
0
import os
import numpy as np
from pil import Image

fname = 'galaga_sprite_sheet.png'
image_dir = 'images'
sprite_sheet = Image.open(os.path.join(image_dir, fname))
im_data = np.array(sprite_sheet)
assert im_data.shape == (383, 424, 3)

# Extract data for each sprite from sprite sheet
sprites = []
for yi in range(12):
    y = 55 + yi * 24
    for xi in range(8):
        x = 16 + xi * 24
        sprite = im_data[y:y + 16, x:x + 16, :]
        sprites.append(sprite)

# Add a border and save as individual files
for i, sprite in enumerate(sprites):
    img_data = np.zeros((19, 19, 3), dtype='uint8')
    img_data[2:18, 2:18, :] = sprite
    img = Image.fromarray(img_data)
    if sprite.sum() > 0:
        img.save(os.path.join(image_dir, f'galaga_{i:02d}.png'))
# Adding label into the frame
l0 = tkinter.Label(root, text="")
l0.pack()

# adding label with different font and formatting
l1 = tkinter.Label(root,
                   text="Hello...!",
                   fg="light green",
                   bg="dark green",
                   font="Helvetica 16 bold italic")
l1.pack()

# images
dice = ['die1.png', 'die2.png', 'die3.png', 'die4.png', 'die5.png', 'die6.png']
# simulating the dice with random numbers between 0 to 6 and generating image
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))

# construct a label widget for image
label1 = tkinter.Label(root, image=image1)
label1.image = image1

# packing a widget in the parent widget
label1.pack(expand=True)


# function activated by button
def rolling_dice():
    image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
    # update image
    label1.configure(image=image1)
    # keep a reference
Пример #31
0
# Create the ST7789 display:
disp = st7789.ST7789(spi,
                     cs=cs_pin,
                     dc=dc_pin,
                     rst=reset_pin,
                     baudrate=BAUDRATE,
                     width=135,
                     height=240,
                     x_offset=53,
                     y_offset=40)

# Create blank image for drawing.
# Make sure to create image with mode 'RGB' for full color.
height = disp.width  # we swap height/width to rotate it to landscape!
width = disp.height
image = Image.new('RGB', (width, height))
rotation = 90

# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)

# Draw a black filled box to clear the image.
draw.rectangle((0, 0, width, height), outline=0, fill=(0, 0, 0))
disp.image(image, rotation)
# Draw some shapes.
# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height - padding
# Move left to right keeping track of the current x position for drawing shapes.
x = 0
Пример #32
0
from tkinter import *
from pil import Image, ImageTk

root = Tk()
root.option_add("*Font", "consolas 25")

images = ['phumin-1', 'phumin-2', 'phumin-3']
imag_list = []
for i, ing in enumerate(images):
    imag_list.append(ImageTk.PhotoImage(Image.open(f'{ing}.jpg')))
    lbl = Label(image=imag_list[i])
    lbl.grid(row=0, column=i)
    Label(root, text=f'{ing}.jpg').grid(row=1, column=i)
root.mainloop()
def rolling_dice():
    image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
    # update image
    label1.configure(image=image1)
    # keep a reference
    label1.image = image1
Пример #34
0
from pil import Image, ImageDraw, ImageFont

def add_num(img):
    draw = ImageDraw.Draw(img)
    myfont = ImageFont.truetype('C:/windows/fonts/Arial.ttf', size=40)
    fillcolor = "#ff0000"
    width, height = img.size
    draw.text((width-40, 0), '99', font=myfont, fill=fillcolor)
    img.save('result.jpg', 'jpeg')

    return 0
if __name__ == '__main__':
    image = Image.open('C:\Users\Administrator\Pictures\zoro.jpg')
    add_num(image)