def pintar_imagen(): ancho = 300 alto = 200 img = Image.open('imagentiempo1.png', "rb") img.thumbnail((ancho, alto), Image.ANTIALIAS) imagen1 = ImageTk.PhotoImage(img) label1 = Label(ventana, image=imagen1, width=ancho, height=alto).place(x=1, y=75) img2 = Image.open('imagenfreq.png', "rb") img2.thumbnail((ancho, alto), Image.ANTIALIAS) imagen2 = ImageTk.PhotoImage(img2) label2 = Label(ventana, image=imagen2, width=ancho, height=alto).place(x=310, y=75) img3 = Image.open('imagenbode.png', "rb") img3.thumbnail((ancho, alto), Image.ANTIALIAS) imagen3 = ImageTk.PhotoImage(img3) label3 = Label(ventana, image=imagen3, width=ancho, height=alto).place(x=620, y=75) img4 = Image.open('filtrado.png', "rb") img4.thumbnail((ancho, alto), Image.ANTIALIAS) imagen4 = ImageTk.PhotoImage(img4) label4 = Label(ventana, image=imagen4, width=ancho, height=alto).place(x=620, y=280) img5 = Image.open('filtradoFFT.png', "rb") img5.thumbnail((ancho, alto), Image.ANTIALIAS) imagen5 = ImageTk.PhotoImage(img5) label5 = Label(ventana, image=imagen5, width=ancho, height=alto).place(x=620, y=490) Image.show()
def display_img(img: Image): """ Given an Image instance, display result :param img: PIL.Image instance :return: None """ img.show()
def openfile(): filename = askopenfilename(parent=root) img = ImageTk.PhotoImage(Image.open(filename)) print(filename) panel = Label(root, image = img) panel.pack(side = "bottom", fill = "both", expand = "yes") Image.show()
def Fourier(): filename = askopenfilename(parent=root) img = Image.open(filename) fft = np.log(np.abs(np.fft.fftshift(np.fft.fft(img)))) panel = Label(root, image = ImageTk.PhotoImage(fft)) panel.pack(side = "bottom", fill = "both", expand = "yes") Image.show()
def find_white_squers(img: Image): width, hight = img.size split = img.split()[2] pix = split.load() ws = [] cv_img = np.array(img) h, w = cv_img.shape[:2] mask = np.zeros((h + 2, w + 2), np.uint8) rect_width, rec_hight = int(width / 10), int(hight / 10) size = lambda i, j: (max(i - rect_width, 0), max(j - rec_hight, 0), min(rect_width + i, width), min(rec_hight + j, hight)) for i in range(rect_width, int(width - rect_width / 4), int(rect_width / 4)): for j in range(rec_hight, int(hight - rec_hight / 4), int(rec_hight / 4)): image_crop = split.crop(size(i, j)) stat = ImageStat.Stat(image_crop) white_thresh = (np.array(stat.mean) + np.array(stat.stddev)) if (pix[i, j] > white_thresh): #image_crop.show() diff = (255, 255, int(white_thresh / 10)) _, _, _, rect = cv2.floodFill(cv_img, mask=mask, seedPoint=(i, j), newVal=255, loDiff=diff, upDiff=diff, flags=cv2.FLOODFILL_FIXED_RANGE) ws.append((rect, white_thresh)) #cv2.imshow('subpixel5.png', cv_img) # filter rects ws = [((r[0][0], r[0][1], r[0][0] + r[0][2], r[0][1] + r[0][3]), white_thresh) for r in ws if rec_hight > r[0][3] > (rec_hight / 7) and (rect_width * 2) > r[0][2] > (rect_width / 1.7)] for r1 in ws: for r2 in ws: if (r1[0] != r2[0]): if (all( abs(r1v - r2v) < (rect_width / 2) for r1v, r2v in zip(r1[0], r2[0]))): ws.remove(r2) # if(len(ws) < 25): # assert (False) # return find_white_squers(img) # print(ws) # print(len(ws)) imgD = ImageDraw.Draw(img) res = [] for w in ws: res.append((w[0], img.crop(w[0]), w[1])) imgD.rectangle(w[0], outline="red", fill="yellow") img.show() return res
class Image: """Represents the raw formt of an image that is loaded""" def __init__(self, path): self.path = path self.form = path[-3:].capitalize() self.pil = Image(path) def __repr__(self): return """ Path: {}, Height:{}, Width: {}, Color Mode: {}, Format: {} """.format(self.path, self.pil.height, self.pil.width, self.pil.mode, self.form) def __str__(self): return """ \nPath: {}, \nHeight:{}, \nWidth: {}, \nColor Mode: {}, \nFormat: {} """.format(self.path, self.pil.height, self.pil.width, self.pil.mode, self.form) def plot(self): self.pil.show()
def computeFourierTransforms(self, resultbmp): self.fourierTransform.setImage(self.image.image) fimg = Image() fimg.set( np.log( np.abs( self.fourierTransform.shift( self.fourierTransform.forwardTransform()))**2)) fimg.show(resultbmp)
def Normal(File_Name): password = input("password for that file: ") encryptor = get_encrypt(password) fileHandle = open_file(File_Name) if (False == fileHandle): FailedToOpenFile = input( "Failed to find %s. Do you want to create a file with this name and password? (Yes/No): " % (File_Name)) if (yesMatch.match(FailedToOpenFile)): fileHandle = open_file(File_Name, force=True, encryptor=encryptor) if (noMatch.match(FailedToOpenFile)): exit(1) DataBase = pickle.loads(encryptor.decrypt(fileHandle.read())) fileHandle.close() while True: print("Do you want to") print( "1. View Database\n2. Add to the Database\n3. Delete items\n4. or exit the program" ) choice = input(" type 1, 2, 3, or 4: ") if int(choice) == 1: for element in DataBase: if (isinstance(element, str)): print(element) elif (isinstance(element, dict)): Image.show(element["Image"]) elif int(choice) == 2: TextOrImage = input( 'do you want to add text or an image? (Text/Image) ') if (textMatch.match(TextOrImage)): # do something with text choice = input('Type first thing to add to database: ') DataBase.append(choice) elif (imageMatch.match(TextOrImage)): # do something with an image AddImage = input("what is the path to the Image file?") im = Image.open(AddImage) DataBase.append({"Image": im.tobytes(encoder_name='raw')}) else: print("What?") write_file(File_Name, DataBase, encryptor) elif int(choice) == 3: print(DataBase) choice = input("\n\nWhich Item to delete? Enter name ") DataBase.remove(choice) write_file(File_Name, DataBase, encryptor) elif int(choice) == 4: exit(0)
def im_cov_cifar10(image): reshaped_image = tf.cast(image, tf.float32) height = IMAGE_SIZE width = IMAGE_SIZE resized_image = tf.image.resize_image_with_crop_or_pad( reshaped_image, width, height) float_image = tf.image.per_image_standardization(resized_image) image = Image(float_image) image.show()
def wait_qr_value(self, qr_img: Image) -> str: if __file__.endswith(".ipynb"): plt.axis("off") plt.imshow(qr_img) plt.show() else: SCALE = 4 qr_img.resize((qr_img.width * SCALE, qr_img.width * SCALE), Image.ANTIALIAS) qr_img.show() return input("Verify Code: ")
def decoupe(image, x, y, taille_capteur_long, taille_capteur_hauteur, xh, xb, yd, yg): #Cette méthode renvoie une image découpée à partir des coordonnées (x,y) ainsi que la taille du capteur try: test(image, x, y, taille_capteur_long, taille_capteur_hauteur) test007(image, x, y, taille_capteur_long, taille_capteur_hauteur) box = (x, y, x + taille_capteur_long, y + taille_capteur_hauteur) coupe = image.crop(box) Image.show(coupe) return (coupe) except MyException as e: print(e) exit()
def upload_image(): global img filepath = filedialog.askopenfilename(initialdir="/", title="Select A File", filetype=(("jpeg", "*.jpg"), ("png", "*.png"))) img = Image.open(filepath) label_width = label.winfo_width() label_height = label.winfo_height() maxsize = (label_width, label_height) resized_original = img.resize(maxsize, Image.ANTIALIAS) ph_original = ImageTk.PhotoImage(img) label['image'] = ph_original Image.show()
def show(self): img = Image(self.video_id, self.timestamp).pil_image() draw = PIL.ImageDraw.Draw(img) draw.rectangle([(self.x, self.y), (self.x+self.width, self.y+self.height)]) if self.face_info: parts = self.face_info.parts for i in range(0,len(parts),2): box = [(parts[i]-1, parts[i+1]-1),(parts[i]+1, parts[i+1]+1)] draw.ellipse(box) for i, j in [(0,1), (2,3), (1,2), (7,8)]: x = (parts[2*i] + parts[2*j])/2 y = (parts[2*i+1] + parts[2*j+1])/2 box = [x-1, y-1, x+1, y+1] draw.ellipse(box) img.show() del draw
def get_image(driver, div): ''' 下载并还原图片 :driver:webdriver :div:图片的div ''' pass # 找到图片所在的div background_images = driver.find_elements_by_css_selector(div) location_list = [] print(len(background_images)) imageurl = '' for background_image in background_images: location = {} # 在html里面解析出小图片的url地址,还有长高的数值 location['x'] = int( re.findall( "background-image: url\(\"(.*)\"\); background-position: (.*)px (.*)px;", background_image.get_attribute('style'))[0][1]) print(location['x']) location['y'] = int( re.findall( "background-image: url\(\"(.*)\"\); background-position: (.*)px (.*)px;", background_image.get_attribute('style'))[0][2]) imageurl = re.findall( "background-image: url\(\"(.*)\"\); background-position: (.*)px (.*)px;", background_image.get_attribute('style'))[0][0] location_list.append(location) imageurl = imageurl.replace("webp", "jpg") jpgfile = io.BytesIO(requests.get(imageurl).content) # 重新合并图片 image = get_merge_image(jpgfile, location_list) image.show() return image
from PIL import Image Image = Image.open('fibonacci_beard.jpg') # must be in same folder width, height = Image.size pixels = Image.load() for i in range(width): for j in range(height): r, g, b = pixels[i, j] r, g, b = int(r), int(g), int(b) y = sum([r, g, b]) // 3 pixels[i, j] = (y, y, y) Image.show()
def show(): image.show()
def takeScreenShot(): Image = ImageGrab.grab().convert('L') Image.show() return Image
def preview_pil(img: PIL.Image): img.show() input(f'bbox is {unpad_bbox(img)}')
def show_image(image: Image, opencv=False): image.show() if not opencv else _show_image_cv('image', image)
# -*- coding: utf-8 -*- """ Created on Wed Jun 3 10:49:58 2015 @author: Marina """ # This script is to change the color view of an image, in can change to black and white, tosepia, to red or militar green. from PIL import Image img = Image('street.JPG') img.show()
from PIL import Image qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data('https://zwmusic.herokuapp.com') qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") print(img) Image.show(img) img.save('zwapp.png')
def show_img(image): Image.show(image)
im_p = copy.deepcopy(self.img) height, width = im_p.shape[:2] w = 0 for h in xrange(int(height)): while int(width) >= w | self.spin1.value() != 0: p_data = poisson(lam=self.spin1.value()) w+=int(p_data) try: im_p[h,w] = [0,0,0] except: pass w = 0 cv2.imshow("poisson_noise",im_p) def hanamegane(self): self.face_know() from PIL import Image layer1 = Image.open(self.fname) layer2 = Image.open('megane.png') layer1 = layer1.convert('RGBA') temp_c = Image.new('RGBA',layer1.size,(255,255,255,0)) for (x, y, w, h) in self.face: resize_megane = layer2.resize((w,h)) temp_c.paste(resize_megane,(x,y),resize_megane) result = Image.alpha_composite(layer1,temp_c) result.show() if __name__ == "__main__": sys.stdout = codecs.getwriter("utf-8")(sys.stdout) app = QApplication(sys.argv) wi = Image() wi.show() app.exec_()
import numpy as np import cv2 from PIL import Image image = cv2.imread("001.jpg") faceCascade = cv2.CascadeClassifier('tongue_cascade.xml') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.65, #该参数需要根据自己训练的模型进行调参 minNeighbors=3, #控制误检测,为3表明至少要3次重叠检测,才认为舌头存在 minSize=(30, 30), #寻找舌头的最小区域。 flags=cv2.IMREAD_GRAYSCALE) cropBox = () for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) box1 = (x, y, x + w, y + h) # 设置舌体矩形框区域 cv2.imwrite("rec001.jpg", image) pil_image = Image.open("rec001.jpg") #使用PIL来编辑图片 image_2 = pil_image.crop(cropBox) # 图像裁剪--根据识别出的特征坐标剪切 Image.show(image2)
def display(self, image: Image): image.show(command='feh')
value) # use decode_png or decode_jpeg decoder based on your files. init_op = tf.initialize_all_variables() with tf.Session() as sess: sess.run(init_op) # Start populating the filename queue. coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(1): #length of your filename list image = my_img.eval() #here is your image Tensor :) print(image.shape) Image.show(Image.fromarray(np.asarray(image))) coord.request_stop() coord.join(threads) def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) # images and labels array as input def convert_to(images, labels, name):
from PIL import Image as im from PIL import ImageFilter as ift i = im.open("winners.jpg") im = i.filter(ift.BLUR) im.show()
def display_image(image: Image): image.show()
args=( plateau, (0, 255, 0), (0, 0, 255), (0.01, 0.01, 0.98), 1, 200000, lock, )) thread_3 = Thread(target=run_ant, args=( plateau, (0, 0, 255), (0, 0, 255), (0.03, 0.02, 0.95), 0.4, 200000, lock, )) thread_1.start() thread_2.start() thread_3.start() thread_1.join() thread_2.join() thread_3.join() Image.show(plateau) plateau.save("plateau.png", "png")
color_lut : opencv compatible color lookup table """ tobits = lambda x, o: np.array(list(np.binary_repr(x, 24)[o::-3]), np.uint8) arr = np.arange(256) r = np.concatenate([np.packbits(tobits(x, -3)) for x in arr]) g = np.concatenate([np.packbits(tobits(x, -2)) for x in arr]) b = np.concatenate([np.packbits(tobits(x, -1)) for x in arr]) return np.concatenate([[[b]], [[g]], [[r]]]).T def labels2rgb(labels, lut): """ Convert a label image to an rgb image using a lookup table :Parameters: labels : an image of type np.uint8 2D array lut : a lookup table of shape (256, 3) and type np.uint8 :Returns: colorized_labels : a colorized label image """ return cv2.LUT(cv2.merge((labels, labels, labels)), lut) if __name__ == '__main__': #labels = np.arange(256).astype(np.uint8)[np.newaxis, :] labels = np.loadtxt('./pics/result_texton_coins_texture3_20201215002820.txt',dtype=np.uint8) lut = gen_lut() print(labels.shape) rgb = labels2rgb(labels, lut) image = image.fromarray(rgb) print(rgb.shape) image.show()
def open_image(image: Image): image.show()
def show_image(img: Image) -> None: # show the PIL image img.show()