コード例 #1
0
def ReadOneImage(filename):
    datain = []
    im = Image.open(filename)
    for y in range(im.size[1]):
        for x in range(im.size[0]):
            datain.append(im.getpixel((x,y)))
    return datain
コード例 #2
0
def best_image_function(name, images_all, images_name):
    highest = 0
    max_width = 0
    max_img = ""
    Ratios = process.extract(name, images_all)
    print(Ratios)
    if Ratios != []:
        highest = process.extractOne(name, images_all)
        #print highest
    if highest[1] < 50:
        Ratios_name = process.extract(name, images_name)
        #print Ratios_name
        if Ratios_name != []:
            highest = process.extractOne(name, images_name)
            if highest[1] > 50:
                return validate_url(images_all[images_name.index(highest[0])])
            else:
                for img in images_all:
                    #print img
                    real_url = validate_url(img)
                    try:
                        file = StringIO.StringIO(
                            urllib.urlopen(real_url).read())
                        im = image.open(file)
                        width, height = im.size
                        if width > max_width:
                            max_width = width
                            max_img = real_url
                        print(width)
                        print(height)
                    except IOError:
                        pass
                return max_img
    else:
        return validate_url(highest[0])
コード例 #3
0
ファイル: views.py プロジェクト: lindsay-show/dzhops
def imageResize(img, username):
    '''
    Image resize to 58 * 58;
    :param img:
    :return:
    '''
    try:
        standard_size = (58, 58)
        file_type = '.jpg'
        user_pic_list = [username, file_type]
        log.debug(str(user_pic_list))
        user_pic_str = ''.join(user_pic_list)
        log.debug('37')
        log.debug('user_pic_path: %s' % str(settings.STATICFILES_DIRS))
        user_pic_path = os.path.join(settings.STATICFILES_DIRS[0], 'img', user_pic_str)
        im = Image.open(img)
        im_new = im.resize(standard_size, Image.ANTIALIAS)
        im_new.save(user_pic_path, 'JPEG', quality=100)
        log.info('The user pic resize successed')
        try:
            all_static = settings.STATIC_ROOT
            all_static_url = os.path.join(all_static, 'img')
        except AttributeError, e:
            all_static_url = ''
            log.info('The config settings.py no STATIC_ROOT attribute')
        if all_static_url and os.path.exists(all_static_url):
            shutil.copy(user_pic_path, all_static_url)
            log.info('The user picture copy to all_static_url')
        else:
            log.debug('The all_static_url is None or do not exist')
コード例 #4
0
def faceCrop(imagePattern, boxScale=1):
    # Select one of the haarcascade files:
    #   haarcascade_frontalface_alt.xml  <-- Best one?
    #   haarcascade_frontalface_alt2.xml
    #   haarcascade_frontalface_alt_tree.xml
    #   haarcascade_frontalface_default.xml
    #   haarcascade_profileface.xml
    faceCascade = cv2.Load(
        r'C:\Users\LeNoVo T430\PycharmProjects\MlLib\haarcascades\haarcascade_frontalface_alt.xml'
    )
    imgList = glob.glob(imagePattern)
    if len(imgList) <= 0:
        print('No Images Found')
        return

    for img in imgList:
        pil_im = image.open(img)
        cv_im = pil2cvGrey(pil_im)
        faces = DetectFace(cv_im, faceCascade)
        if faces:
            n = 1
            for face in faces:
                croppedImage = imgCrop(pil_im, face[0], boxScale=boxScale)
                fname, ext = os.path.splitext(img)
                croppedImage.save(fname + '_crop' + str(n) + ext)
                n += 1
        else:
            print('No faces found:', img)
コード例 #5
0
 def resize_by_width(source_image, destination_image, w_divide_h):
     """按照宽度进行所需比例缩放"""
     im = image.open(source_image)
     (x, y) = im.size
     x_s = x
     y_s = x / w_divide_h
     out = im.resize((x_s, y_s), image.ANTIALIAS)
     out.save(destination_image)
コード例 #6
0
 def resize_by_height(source_image, destination_image, w_divide_h):
     """按照高度进行所需比例缩放"""
     im = image.open(source_image)
     (x, y) = im.size
     x_s = y * w_divide_h
     y_s = y
     out = im.resize((x_s, y_s), image.ANTIALIAS)
     out.save(destination_image)
コード例 #7
0
ファイル: preprocessor.py プロジェクト: THUBrick-Movers/SVHN
 def __getitem__(self, index):
     img = image.open(self.img_path[index]).convert('RGB')
     if self.transforms is not None:
         img = self.transforms(img)
     # 设置最长的字符长度为6个
     lbl = np.array(self.img_label[index], dtype=np.int)
     # 使用10填充剩余的位置
     lbl = list(lbl) + (6 - len(lbl)) * [10]
     return img, torch.from_numpy(np.array(lbl[:6]))
コード例 #8
0
def setWallPaper(imagePath):
    """
    Given a path to an image, convert it to bmp and set it as wallpaper
    """

    bmpImage = image.open(imagePath)
    newPath = StoreFolder + '\\mywallpaper.bmp'
    bmpImage.save(newPath, "BMP")
    setWallpaperFromBMP(newPath)
コード例 #9
0
def ReadImages():
    datain = []
    for infile in glob.glob("*.pgm"):
        #filename, ext = os.path.splitext(infile)
        #print filename
        im = Image.open(infile)
        pixels = []
        for y in range(im.size[1]):
            for x in range(im.size[0]):
                pixels.append(im.getpixel((x,y)))
        datain.append(pixels)
    return datain
コード例 #10
0
def save_picture(form_file, folder_name):
    random_hex = random.token_hex(8)
    _, f_ext = os.path.splitext(form_file.filename)
    picture_fn = random_hex + f_ext
    picture_path = os.path.join(current_app.root_path, 'static', folder_name,
                                picture_fn)

    output_size = (125, 125)
    i = image.open(form_file)
    i.thumbnail(output_size)
    i.save(picture_path)

    return picture_fn
コード例 #11
0
def read_2d_data(f):
    if f.endswith('.dat'): return read_dat(f)
    if f.endswith('.txt'): return loadtxt(f, dtype=float32)
#    if f.endswith('.dcm'): return read_dicom(f)
    if f.endswith('.mat'): return read_matlab(f)
    if f.endswith('.mtx'): return read_mtx(f)
    if f.endswith('.npz') or f.endswith('.npy'): return read_numpy(f)
    if any([f.endswith(e) for e in ['.png', '.PNG', '.jpg', '.JPG', '.jpeg', '.JPEG', '.bmp', '.BMP', '.PGM', '.tif', '.TIF']]):
		img = Image.open(f)
		tmp = numpy.asarray(img)
		return tmp
    if f.endswith('.nrrd'): return read_nrrd(f)
    assert False, "unknown file type: " + f
コード例 #12
0
 def resize_by_size(source_image, destination_image, size):
     """按照生成图片文件大小进行处理(单位KB)"""
     size *= 1024
     im = image.open(source_image)
     size_tmp = os.path.getsize(source_image)
     q = 100
     while size_tmp > size and q > 0:
         out = im.resize(im.size, image.ANTIALIAS)
         out.save(destination_image, quality=q)
         size_tmp = os.path.getsize(destination_image)
         q -= 5
     if q == 100:
         shutil.copy(source_image, destination_image)
コード例 #13
0
def main(): 
    try: 
        #Relative Path 
        img = image.open("a.jpg")  
          
        #Angle given 
        img = img.rotate(180)  
          
         #Saved in the same relative location 
        img.save("rotated_picture.jpg") 
        
        detect_web(img)
    except IOError: 
        pass
コード例 #14
0
def test(imageFilePath):
    pil_im = image.open(imageFilePath)
    cv_im = pil2cvGrey(pil_im)
    # Select one of the haarcascade files:
    #   haarcascade_frontalface_alt.xml  <-- Best one?
    #   haarcascade_frontalface_alt2.xml
    #   haarcascade_frontalface_alt_tree.xml
    #   haarcascade_frontalface_default.xml
    #   haarcascade_profileface.xml
    faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
    face_im = DetectFace(cv_im, faceCascade, returnImage=True)
    img = cv2pil(face_im)
    img.show()
    img.save('test.png')
コード例 #15
0
ファイル: get_head_image.py プロジェクト: yuanmin1992/test_py
def createImg():
    x = 0
    y = 0
    imgs = os.listdir("img")
    random.shuffle(imgs)
    newImg = image.new("RGBA", (640, 640))
    width = int(math.sqrt(640 * 640 / len(imgs)))
    numLine = int(640 / width)

    for i in imgs:
        img = image.open("img/" + i)
        img = img.resize((width, width), image.ANTIALIAS)
        newImg.paste(img, (x * width, y * width))
        x += 1
        if x >= numLine:
            x = 0
            y += 1
    newImg.save("all.png")
コード例 #16
0
    def cut_by_ratio(source_image, destination_image, width, height):
        """按照图片长宽比进行分割"""
        im = image.open(source_image)
        width = float(width)
        height = float(height)
        (x, y) = im.size
        if width > height:
            region = (0, int((y - (yi * (height / width))) / 2), x,
                      int((y + (y * (height / width))) / 2))
        elif width < height:
            region = (int((x - (x * (width / height))) / 2), 0,
                      int((x + (x * (width / height))) / 2), y)
        else:
            region = (0, 0, x, y)

        #裁切图片
        crop_img = im.crop(region)
        #保存裁切后的图片
        crop_img.save(destination_image)
コード例 #17
0
    def post(self, template_variables={}):
        template_variables = {}

        if (not "avatar" in self.request.files):
            template_variables["errors"] = {}
            template_variables["errors"]["invalid_avatar"] = [u"请先选择要上传的头像"]
            self.get(template_variables)
            return

        user_info = self.current_user
        user_id = user_info["uid"]
        avatar_name = "%s" % uuid.uuid5(uuid.NAMESPACE_DNS, str(user_id))
        avatar_raw = self.request.files["avatar"][0]["body"]
        avatar_buffer = StringIO.StringIO(avatar_raw)
        avatar = image.open(avatar_buffer)

        # crop avatar if it's not square
        avatar_w, avatar_h = avatar.size
        avatar_border = avatar_w if avatar_w < avatar_h else avatar_h
        avatar_crop_region = (0, 0, avatar_border, avatar_border)
        avatar = avatar.crop(avatar_crop_region)

        avatar_96x96 = avatar.resize((96, 96), image.ANTIALIAS)
        avatar_48x48 = avatar.resize((48, 48), image.ANTIALIAS)
        avatar_32x32 = avatar.resize((32, 32), image.ANTIALIAS)
        avatar_96x96.save(
            "/srv/www/3n1b.com/static/avatar/b_%s.png" % avatar_name, "PNG")
        avatar_48x48.save(
            "/srv/www/3n1b.com/static/avatar/m_%s.png" % avatar_name, "PNG")
        avatar_32x32.save(
            "/srv/www/3n1b.com/static/avatar/s_%s.png" % avatar_name, "PNG")
        result = self.user_model.set_user_avatar_by_uid(
            user_id, "%s.png" % avatar_name)
        template_variables["success_message"] = [u"用户头像更新成功"]
        # update `updated`
        updated = self.user_model.set_user_base_info_by_uid(
            user_id, {"updated": time.strftime('%Y-%m-%d %H:%M:%S')})
        self.get(template_variables)
コード例 #18
0
ファイル: functions.py プロジェクト: parulian1/foundation
def rescale(data, width, height, force=True):
    """Rescale the given image, optionally cropping it to make sure the result image has the specified width and height."""
    import image as pil
    from cStringIO import StringIO

    max_width = width
    max_height = height

    input_file = StringIO(data)
    img = pil.open(input_file)
    if not force:
        img.thumbnail((max_width, max_height), pil.ANTIALIAS)
    else:
        img = ImageOps.fit(img, (max_width, max_height), method=pil.ANTIALIAS)

    tmp = StringIO()
    img.save(tmp, "PNG")
    tmp.seek(0)
    output_data = tmp.getvalue()
    input_file.close()
    tmp.close()

    return output_data
コード例 #19
0
ファイル: functions.py プロジェクト: parulian1/foundation
def rescale(data, width, height, force=True):
	"""Rescale the given image, optionally cropping it to make sure the result image has the specified width and height."""
	import image as pil
	from cStringIO import StringIO
	
	max_width = width
	max_height = height

	input_file = StringIO(data)
	img = pil.open(input_file)
	if not force:
		img.thumbnail((max_width, max_height), pil.ANTIALIAS)
	else:
		img = ImageOps.fit(img, (max_width, max_height,), method=pil.ANTIALIAS)
		
	tmp = StringIO()
	img.save(tmp, 'PNG')
	tmp.seek(0)
	output_data = tmp.getvalue()
	input_file.close()
	tmp.close()
	
	return output_data
コード例 #20
0
ファイル: dehaze.py プロジェクト: arasharchor/BeyondFilter
# coding=utf-8

# /************************************************************************************
# ***
# ***    File Author: Dell, 2018年 08月 19日 星期日 20:38:18 CST
# ***
# ************************************************************************************/
import sys
import image
import torch


def dehaze_filter(device, img, r=3):
    model = image.DehazeFilter(r)
    model.to(device)
    t = image.to_tensor(img)
    t = model(t)
    return image.from_tensor(t)


if __name__ == '__main__':
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    img = image.open(sys.argv[1])
    img = dehaze_filter(device, img, 5)
    img.show()
コード例 #21
0
def load_image(infilename):
    img = image.open(infilename)
    img.load()
    data = np.asarray(img, dtype="float")
    return data
コード例 #22
0
ファイル: 3-4-4.py プロジェクト: Taliainez/PythonProject
import image
im = image.open("earthEyes.py")


コード例 #23
0
# _*_ coding:utf-8 _*_

# 给定图片位置添加数字
import image
im = image.open("../img/mm.jpg")
print im
コード例 #24
0
ファイル: scan_image.py プロジェクト: Ameyashan/scara
#!/usr/bin/python
from sys import argv
import zbar
import image as Image

print(argv)
if len(argv) < 2: exit(1)

# create a reader
scanner = zbar.ImageScanner()

# configure the reader
scanner.parse_config('enable')

# obtain image data
pil = Image.open(argv[1]).convert('L')
width, height = pil.size
raw = pil.tostring()

# wrap image data
image = zbar.Image(width, height, 'Y800', raw)

# scan the image for barcodes
scanner.scan(image)

# extract results
for symbol in image:
    # do something useful with results
    print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data

# clean up
コード例 #25
0
ファイル: craw_wave.py プロジェクト: kobv4279/web2-python
from flask import Flask, render_template, request
import requests
from bs4 import BeautifulSoup
import datetime
import selenium
from selenium import webdriver
import image
#https://www.weather.go.kr/mini/marine/wavemodel_c.jsp?prefix=kim_cww3_%5BAREA%5D_wdpr_&area=jeju&tm=2020.04.28.09&ftm=s000&newTm=2020.04.28.09&x=4&y=10

a = input("날짜")

url = "https://www.weather.go.kr/mini/marine/wavemodel_c.jsp?prefix=kim_cww3_%5BAREA%5D_wdpr_&area=jeju&tm=" + a

driver = webdriver.Chrome()
driver.implicitly_wait(3)
driver.get(url)

soup = BeautifulSoup(driver.page_source, "html.parser")

for i in soup.select("#chart_image"):
    src = i.find("img")['src']

image = image.open(src)
image.show()
コード例 #26
0
ファイル: Aes.py プロジェクト: switch87/basicSecurity
 def save_in_image(self, string, image_file, out_file):
     if out_file[-4:] != ".png":
         show_message("The output file should be a png-image")
     image1 = image.open(image_file)
     image2 = stepic.encode(image1, string)
     image2.save(out_file)
コード例 #27
0
ファイル: extractRGB.py プロジェクト: rcj9719/arin
import image

def color_separator(im):
    if im.getpalette():
        im = im.convert('RGB')

    colors = im.getcolors()
    width, height = im.size
    colors_dict = dict((val[1],image.new('RGB', (width, height), (0,0,0)))
                        for val in colors)
    pix = im.load()
    for i in xrange(width):
        for j in xrange(height):
            colors_dict[pix[i,j]].putpixel((i,j), pix[i,j])
    return colors_dict

im = image.open("colorwheel.tiff")
colors_dict = color_separator(im)
#show the images:
colors_dict.popitem()[1].show()
colors_dict.popitem()[1].show()
コード例 #28
0
    parser.add_argument('--input',
                        type=str,
                        default="hazeimgs/*.jpg",
                        help="input image")
    parser.add_argument('--output',
                        type=str,
                        default="output",
                        help="output directory")
    args = parser.parse_args()

    # Create directory to store results
    if not os.path.exists(args.output):
        os.makedirs(args.output)

    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    model = dehaze_filter(3, device)

    image_filenames = glob.glob(args.input)

    for index, filename in enumerate(image_filenames):
        print("Dehazing {} ... ".format(filename))

        img = image.open(filename)

        input_tensor = image.to_tensor(img)
        output_tensor = model(input_tensor)

        oimg = image.grid_image([input_tensor, output_tensor], nrow=2)
        oimg.save(args.output + "/dehaze_" + os.path.basename(filename))
コード例 #29
0
ファイル: css.py プロジェクト: roytest001/PythonCode
    string = '%dpx %dpx 0px 1px rgb%s,\n'
    for y in range(0, im.size[1], 1):
        for x in range(0, im.size[0], 1):
            if im.size[1] - y <= 1 and im.size[0] - x <= 1:
                string = '%dpx %dpx 0px 1px rgb%s;\n'
            color = im.getpixel((x, y))
            css += string % (x, y, color)
    return css


def gethtml(css):
    """docstring for gethtml"""
    html = """
    <div style="
    %s"></div>
    """ % css
    return html


if __name__ == '__main__':
    filename = sys.argv[1]
    #outfile = sys.argv[2]
    im = image.open(filename)
    ratio = 0.5
    size = (int(ratio * im.size[0]), int(ratio * im.size[1]))
    im.thumbnail(size)
    html = gethtml(getcss(im))
    print html
    # with open(outfile, 'wb') as f:
    #     f.write(html)__author__ = 'royxu'
コード例 #30
0
img = plt.imread('G:\\个人资料\\图库\\桌面\\112.jpg')
img = plt.imread('G:\\个人资料\\图库\\桌面\\1111.png')
imshow(img)
img
get_ipython().magic('matplotlib inline')
import pandas as pd
import image

get_ipython().magic('matplotlib inline')
import pandas as pd
import image

imshow(img)
img.show()
img = image.open('G:\\个人资料\\图库\\桌面\\1111.png')
img = plt.imread('G:\\个人资料\\图库\\桌面\\1111.png')
plt.imshow(img)
plt(randn(1000).cumsum())
get_ipython().magic('matplotlib inline')
import pandas as pd
import image
from numpy.random import randn
import numpy as np
import os
import matplotlib.pyplot as plt

img = plt.imread('G:\\个人资料\\图库\\桌面\\1111.png')
plt.imshow(img)
plt(randn(1000).cumsum())
a = plt(randn(1000).cumsum())
コード例 #31
0
ファイル: Aes.py プロジェクト: switch87/basicSecurity
 def extract_from_image(self, image_file, out):
     file = open(out, 'w')
     file.write(stepic.decode(image.open(image_file)))
コード例 #32
0
 now we need to merge all file
 """
 pathsave = []
 print('A')
 try:
     #search all image in temp path. file name ends with uuid_set value
     # new_folder_name = (os.path.basename(filepdf)).split('.PDF')[0]
     # print(new_folder_name)
     # new_folder_path = "/home/hjiang/superlist/pdftoimage/%s" % new_folder_name
     # print(new_folder_path)
     # os.makedirs(new_folder_path)
     list_im = glob.glob(new_folder_path + "/%s*.jpeg" % uuid_set)
     print('B')
     list_im.sort()  #sort the file before joining it
     print('C')
     imgs = [Img.open(i) for i in list_im]
     print('D')
     #now lets Combine several images vertically with Python
     min_shape = sorted([(np.sum(i.size), i.size) for i in imgs])[0][1]
     print('E')
     imgs_comb = np.vstack(
         (np.asarray(i.resize(min_shape)) for i in imgs))
     print('F')
     # for horizontally  change the vstack to hstack
     imgs_comb = Img.fromarray(imgs_comb)
     print('G')
     pathsave = new_folder_path + "MyPdf%s.jpeg" % uuid_set
     print('H')
     #now save the image
     imgs_comb.save(pathsave)
     print('I')
コード例 #33
0
"""
Created on Tue Oct  2 13:23:48 2018

@author: Tayro
"""

import numpy as np
import matplotlib.pyplot as mplot

import image

img = Image.open("mgb.jpg")
img=np.float64(img)


img1=image.open("jag.jpg")
img1=np.gloat64(img1)

avg_img=img+img1

avg_img=avg_img/2.0

for row in range(0, len(avg_img)):
    for col in range(0, len(avg_img[row])):
        if(avg_img[row][col] < [100, 100, 100]).any()
            

avg_img=np.clip(avg_img, 0, 255)
avg_img=np.uint8(avg_img)

mplot.imshow(avg_img)
コード例 #34
0
 def fixed_size(source_image, destination_image, width, height):
     """按照固定尺寸处理图片"""
     im = image.open(source_image)
     out = im.resize((width, height), image.ANTIALIAS)
     out.save(destination_image)
コード例 #35
0
ファイル: magic.py プロジェクト: tech-projects/clustering
def main(conf):
    img = image.open(conf.file)
    segments = image.segment(img, int(conf.cluster), it=5)
    image.save('./output/' + str(time.time()), segments)