def test_image_formats(self):
        """make sure the scales have the same format as the original image
        """

        from cStringIO import StringIO
        from PIL.Image import open
        org_data = StringIO(self.img.image.data)
        self.assertEqual(open(org_data).format, 'PNG')

        view = self.img.restrictedTraverse('@@crop-image')
        view._crop(fieldname='image', scale='thumb', box=(14, 14, 218, 218))
        traverse = self.portal.REQUEST.traverseName

        scales = traverse(self.img, '@@images')
        cropped = scales.scale('image', 'thumb')
        croppedData = StringIO(cropped.data._data)
        self.assertEqual(
            open(croppedData).format, 'PNG',
            'cropped scale does not have same format as the original')

        # create a jpeg image out of the png file
        # and test if created scale is jpeg too
        _createObjectByType('Image', self.portal, 'testjpeg')
        jpg = self.portal.testjpeg
        jpg.image = dummy_named_blob_jpg_image()

        org_data = StringIO(jpg.image.data)
        self.assertEqual(open(org_data).format, 'JPEG')

        view = jpg.restrictedTraverse('@@crop-image')
        view._crop(fieldname='image', scale='thumb', box=(14, 14, 218, 218))
        cropped = scales.scale('image', 'thumb')
        croppedData = StringIO(cropped.data._data)
def neuesBild(path):
	global pix
	global breite
	global höhe
	if isfile(path):
		im = open(path)
		pix = im.load()
		breite, höhe = im.size	#die Breite und die höhe des Bildes wird ausgelesen
		breite = breite /2 	#damit der Koordinatenmittelpunkt in die mitte des Bildes Kommt
		höhe = höhe / 2
	elif isfile(path+ "png"):
		im = open(path + "png")
		pix = im.load()
		breite, höhe = im.size	#die Breite und die höhe des Bildes wird ausgelesen
		breite = breite /2 	#damit der Koordinatenmittelpunkt in die mitte des Bildes Kommt
		höhe = höhe / 2 
	elif isfile(path+"jpg"):
		im = open(path + "jpg")
		pix = im.load()
		breite, höhe = im.size	#die Breite und die höhe des Bildes wird ausgelesen
		breite = breite /2 	#damit der Koordinatenmittelpunkt in die mitte des Bildes Kommt
		höhe = höhe / 2
	elif isfile(path+"jpeg"):
		im = open(path + "jpeg")
		pix = im.load()
		breite, höhe = im.size	#die Breite und die höhe des Bildes wird ausgelesen
		breite = breite /2 	#damit der Koordinatenmittelpunkt in die mitte des Bildes Kommt
		höhe = höhe / 2 	
	else:
		print("Dateityp des Bildes wird nicht unterstützt...")
		sleep(0.01)
예제 #3
0
def neuesBild(path):
    global pix
    global breite
    global höhe
    if isfile(path):
        im = open(path)
        pix = im.load()
        breite, höhe = im.size  #die Breite und die höhe des Bildes wird ausgelesen
        breite = breite / 2  #damit der Koordinatenmittelpunkt in die mitte des Bildes Kommt
        höhe = höhe / 2
    elif isfile(path + "png"):
        im = open(path + "png")
        pix = im.load()
        breite, höhe = im.size  #die Breite und die höhe des Bildes wird ausgelesen
        breite = breite / 2  #damit der Koordinatenmittelpunkt in die mitte des Bildes Kommt
        höhe = höhe / 2
    elif isfile(path + "jpg"):
        im = open(path + "jpg")
        pix = im.load()
        breite, höhe = im.size  #die Breite und die höhe des Bildes wird ausgelesen
        breite = breite / 2  #damit der Koordinatenmittelpunkt in die mitte des Bildes Kommt
        höhe = höhe / 2
    elif isfile(path + "jpeg"):
        im = open(path + "jpeg")
        pix = im.load()
        breite, höhe = im.size  #die Breite und die höhe des Bildes wird ausgelesen
        breite = breite / 2  #damit der Koordinatenmittelpunkt in die mitte des Bildes Kommt
        höhe = höhe / 2
    else:
        print("Dateityp des Bildes wird nicht unterstützt...")
        sleep(0.01)
    def test_image_formats(self):
        """make sure the scales have the same format as the original image
        """

        from cStringIO import StringIO
        from PIL.Image import open
        org_data = StringIO(self.img.image.data)
        self.assertEqual(open(org_data).format, 'PNG')

        view = self.img.restrictedTraverse('@@crop-image')
        view._crop(fieldname='image', scale='thumb', box=(14, 14, 218, 218))
        traverse = self.portal.REQUEST.traverseName

        scales = traverse(self.img, '@@images')
        cropped = scales.scale('image', 'thumb')
        croppedData = StringIO(cropped.data._data)
        self.assertEqual(
            open(croppedData).format,
            'PNG',
            'cropped scale does not have same format as the original'
        )

        # create a jpeg image out of the png file
        # and test if created scale is jpeg too
        _createObjectByType('Image', self.portal, 'testjpeg')
        jpg = self.portal.testjpeg
        jpg.image = NamedBlobImage(data=self._jpegImage())

        org_data = StringIO(jpg.image.data)
        self.assertEqual(open(org_data).format, 'JPEG')

        view = jpg.restrictedTraverse('@@crop-image')
        view._crop(fieldname='image', scale='thumb', box=(14, 14, 218, 218))
        cropped = scales.scale('image', 'thumb')
        croppedData = StringIO(cropped.data._data)
    def test_image_formats(self):
        """make sure the scales have the same format as the original image
        """

        from cStringIO import StringIO
        from PIL.Image import open

        org_data = StringIO(self.img.getImage().data)
        self.assertEqual(open(org_data).format, "PNG")

        view = self.img.restrictedTraverse("@@crop-image")
        view._crop(fieldname="image", scale="thumb", box=(14, 14, 218, 218))
        traverse = self.portal.REQUEST.traverseName
        cropped = traverse(self.img, "image_thumb")
        croppedData = StringIO(cropped.data)
        self.assertEqual(open(croppedData).format, "PNG", "cropped scale does not have same format as the original")

        # create a jpeg image out of the png file:
        img = open(file(join(dirname(tests.__file__), "plone-logo.png")))
        out = StringIO()
        img.save(out, format="JPEG", quality=75)
        out.seek(0)

        # and test if created scale is jpeg too
        _createObjectByType("Image", self.portal, "testjpeg")
        jpg = self.portal.testjpeg
        jpg.setImage(out.getvalue())

        org_data = StringIO(jpg.getImage().data)
        self.assertEqual(open(org_data).format, "JPEG")

        view = jpg.restrictedTraverse("@@crop-image")
        view._crop(fieldname="image", scale="thumb", box=(14, 14, 218, 218))
        cropped = traverse(self.img, "image_thumb")
        croppedData = StringIO(cropped.data)
예제 #6
0
파일: images.py 프로젝트: oew1v07/Medial
def apple():
    if exists("Images/apple.gif"):
        out = np.asarray(open("Images/apple.gif"))
    else:
        out = None

    return out
예제 #7
0
파일: images.py 프로젝트: oew1v07/Medial
def chopper():
    if exists("Images/chopper.gif"):
        out = np.asarray(open("Images/chopper.gif"))
    else:
        out = None

    return out
예제 #8
0
파일: images.py 프로젝트: oew1v07/Medial
def camel():
    if exists("Images/camel.gif"):
        out = np.asarray(open("Images/camel.gif"))
    else:
        out = None

    return out
예제 #9
0
파일: images.py 프로젝트: oew1v07/Medial
def butterfly():
    if exists("Images/butterfly.gif"):
        out = np.asarray(open("Images/butterfly.gif"))
    else:
        out = None

    return out
예제 #10
0
파일: images.py 프로젝트: oew1v07/Medial
def bone():
    if exists("Images/Bone.gif"):
        out = np.asarray(open("Images/Bone.gif"))
    else:
        out = None

    return out
예제 #11
0
def loadImage(imageName):
    """Load an image from a file using PIL.
    This is closer to what you really want to do than the
    original port's crammed-together stuff that set global
    state in the loading method.  Note the process of binding
    the texture to an ID then loading the texture into memory.
    This didn't seem clear to me somehow in the tutorial.
    """
    try:
        from PIL.Image import open
    except ImportError:
        from Image import open
    im = open(imageName)
    # im = im.convert("RGBA")
    try:
        ix, iy, image = im.size[0], im.size[1], im.tobytes("raw", "RGB", 0, -1)
    except SystemError:
        ix, iy, image = im.size[0], im.size[1], im.tobytes("raw", "RGB", 0, -1)
    # generate a texture ID
    ID=glGenTextures(1)
    # make it current
    glBindTexture(GL_TEXTURE_2D, ID)
    glPixelStorei(GL_UNPACK_ALIGNMENT,1)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    # copy the texture into the current texture ID
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, ix, iy, 0, GL_RGB, GL_UNSIGNED_BYTE, image)
    print(ix,iy)
    glGenerateMipmap(GL_TEXTURE_2D)
    # return the ID for use
    return ID
예제 #12
0
def splitimage(src, rownum, colnum, dstpath):
    rownum = int(rownum)
    colnum = int(colnum)
    try:
        img = open(src)
    except BaseException:
        return False
    w, h = img.size
    if rownum <= h and colnum <= w:
        s = os.path.split(src)
        if dstpath == '':
            dstpath = s[0]
        fn = s[1].split('.')
        basename = fn[0]
        ext = fn[-1]
        num = 0
        rowheight = h // rownum
        colwidth = w // colnum
        for r in range(rownum):
            for c in range(colnum):
                box = (c * colwidth, r * rowheight, (c + 1) * colwidth,
                       (r + 1) * rowheight)
                img.crop(box).save(
                    os.path.join(dstpath,
                                 basename + '_' + str(num) + '.' + ext), ext)
                num = num + 1
        return True
    else:
        print("error")
        return False
예제 #13
0
class TestContext(BaseContext):
    def OnInit(self):
        """Load the image on initial load of the application"""
        global multitexture
        multitexture = self.extensions.initExtension("GL.ARB.multitexture")
        if not multitexture:
            print 'GL_ARB_multitexture not supported!'
            sys.exit(1)
        self.image = self.loadImage("nehe_wall.bmp")
        self.lightmap = self.loadLightMap("lightmap1.jpg")

    def loadImage(self, imageName="nehe_wall.bmp"):
        """Load an image from a file using PIL.
        This is closer to what you really want to do than the
        original port's crammed-together stuff that set global
        state in the loading method.  Note the process of binding
        the texture to an ID then loading the texture into memory.
        This didn't seem clear to me somehow in the tutorial.
        """
        try:
            from PIL.Image import open
        except ImportError, err:
            from Image import open
        multitexture.glActiveTextureARB(multitexture.GL_TEXTURE0_ARB)
        return texture.Texture(open(imageName))
예제 #14
0
파일: images.py 프로젝트: oew1v07/Medial
def device2():
    if exists("Images/device2.gif"):
        out = np.asarray(open("Images/device2.gif"))
    else:
        out = None

    return out
예제 #15
0
파일: images.py 프로젝트: oew1v07/Medial
def frog():
    if exists("Images/frog.gif"):
        out = np.asarray(open("Images/frog.gif"))
    else:
        out = None

    return out
예제 #16
0
파일: images.py 프로젝트: oew1v07/Medial
def elephant():
    if exists("Images/elephant.gif"):
        out = np.asarray(open("Images/elephant.gif"))
    else:
        out = None

    return out
예제 #17
0
파일: images.py 프로젝트: oew1v07/Medial
def bell():
    if exists("Images/bell.gif"):
        out = np.asarray(open("Images/bell.gif"))
    else:
        out = None

    return out
예제 #18
0
	def importImageFolder(self,pathF):
		print(pathF)
		y = ConnectionManager('KappaBase.db')
		l=listdir(pathF)

		#get next id
		u=self.cDao.getNextId()

		listImage = self.cDao.getAll()
		listPath =[]
		for im in listImage:
			listPath.append(im.path)

		#file in folder
		for i in l:
			pathName = join(pathF, i)
			print(pathName)
			if(isfile(pathName) and pathName not in listPath):
				print(2, pathName)

				extension = i.split(".")[1]
				if(extension in ("jpeg","jpg","png","PNG","JPEG","JPG")):
					im = open(pathName)
					path = pathName
					size = getsize(path)
					width = im.size[0]
					height = im.size[1]
					date = str(datetime.fromtimestamp(getctime(path)))

					img = ImageModel(u, "", date, height, width, size, path, None, None)
					self.create(img)
					u+=1
예제 #19
0
 def loadImage(self, imageName="nehe_wall.bmp"):
     """Load an image from a file using PIL.
     This is closer to what you really want to do than the
     original port's crammed-together stuff that set global
     state in the loading method.  Note the process of binding
     the texture to an ID then loading the texture into memory.
     This didn't seem clear to me somehow in the tutorial.
     """
     try:
         from PIL.Image import open
     except ImportError:
         from Image import open
     im = open(imageName)
     try:
         ix, iy, image = im.size[0], im.size[1], im.tobytes(
             "raw", "RGBA", 0, -1)
     except (ValueError, SystemError):
         ix, iy, image = im.size[0], im.size[1], im.tobytes(
             "raw", "RGBX", 0, -1)
     # generate a texture ID
     ID = glGenTextures(1)
     # make it current
     glBindTexture(GL_TEXTURE_2D, ID)
     glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
     # copy the texture into the current texture ID
     glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE,
                  image)
     # return the ID for use
     return ID
    def loadImage(self, imageName='8316_128x128.png'):

        #def loadImage( self, imageName = "tnt_25747.png" ):
        """Load an image file as a 2D texture using PIL"""

        # PIL defines an "open" method which is Image specific!
        im = open(imageName)
        try:
            ix, iy, image = im.size[0], im.size[1], im.tobytes(
                "raw", "RGBA", 0, -1)
        except (SystemError, ValueError):
            ix, iy, image = im.size[0], im.size[1], im.tobytes(
                "raw", "RGBX", 0, -1)
        except AttributeError:
            ix, iy, image = im.size[0], im.size[1], im.tostring(
                "raw", "RGBX", 0, -1)

        # Generate a texture ID
        ID = glGenTextures(1)

        # Make our new texture ID the current 2D texture
        glBindTexture(GL_TEXTURE_2D, ID)
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1)

        # Copy the texture data into the current texture ID
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA,
                     GL_UNSIGNED_BYTE, image)

        glGenerateMipmap(GL_TEXTURE_2D)

        # Note that only the ID is returned, no reference to the image object or the
        # string data is stored in user space.
        # The data is only present within the GL after this call exits.
        return ID
예제 #21
0
    def loadImage(self, imageName="nehe_wall.bmp"):
        """Load an image file as a 2D texture using PIL"""
        # PIL defines an "open" method which is Image specific!
        im = open(imageName)
        try:
            ix, iy, image = im.size[0], im.size[1], im.tostring(
                "raw", "RGBA", 0, -1)
        except SystemError:
            ix, iy, image = im.size[0], im.size[1], im.tostring(
                "raw", "RGBX", 0, -1)
        # Generate a texture ID
        ID = glGenTextures(1)

        # Make our new texture ID the current 2D texture
        glBindTexture(GL_TEXTURE_2D, ID)
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1)

        # Copy the texture data into the current texture ID
        glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE,
                     image)
        """
        Note that only the ID is returned, no reference to the image object
        or the string data is stored in user space, the data is only present
        within the GL after this call exits.
        """
        return ID
예제 #22
0
파일: main.py 프로젝트: MrValdez/Panoromic
def generate_texture():
    glEnable(GL_TEXTURE_2D)
    textures = []

    for file in ["bg_vh.jpg", "bg_h.jpg", "bg.jpg"]:
        im = open(file)
        try:
            ix, iy, image = im.size[0], im.size[1], im.tostring(
                "raw", "RGBA", 0, -1)
        except SystemError:
            ix, iy, image = im.size[0], im.size[1], im.tostring(
                "raw", "RGBX", 0, -1)

        for filter, filter_name in ((GL_NEAREST, "Nearest"), (GL_LINEAR,
                                                              "Linear")):
            texture = glGenTextures(1)
            glBindTexture(GL_TEXTURE_2D, texture)
            glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
            glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA,
                         GL_UNSIGNED_BYTE, image)

            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter)
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter)
            glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)

            data = (texture, file, filter_name)
            textures.append(data)

    create_pygame_surface_texture()
    return textures
예제 #23
0
    def load_texture(self):
        print("loading truck texture")
        metalImage = open("metal.jpg")

        ix = metalImage.size[0]
        iy = metalImage.size[1]
        metalImage = metalImage.tobytes("raw", "RGB", 0, -1)

        carTexture = glGenTextures(1)

        glBindTexture(GL_TEXTURE_2D, carTexture)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, ix, iy, 0, GL_RGB,
                     GL_UNSIGNED_BYTE, metalImage)

        glEnable(GL_TEXTURE_2D)

        light_ambient = [0.5, 0.5, 0.5, 1.0]
        light_diffuse = [1.0, 1.0, 1.0, 1.0]
        light_position = [0.0, 1.0, 1.0, 1.0]

        glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient)
        glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse)
        glLightfv(GL_LIGHT1, GL_POSITION, light_position)

        glEnable(GL_LIGHTING)
        glEnable(GL_LIGHT1)

        glEnable(GL_COLOR_MATERIAL)

        glDepthFunc(GL_LESS)
        glEnable(GL_DEPTH_TEST)
예제 #24
0
def load_hd_new(file_path, meta=None, **kwargs):
    """Load new format from Heidelberg group.

    This format contains IPTC information

    :param file_path: image file path
    :param dict meta: optional, meta info dictionary to which additional meta
        information is supposed to be appended
    :return:
        - ndarray, image data
        - dict, dictionary containing meta information
    """
    if meta is None:
        meta = {}
    try:
        from PIL.Image import open
        read = open(file_path)
        meta["texp"] = float(read.tag_v2[270].split(" ")[0].split("s")[0])
        img = asarray(read)
    except ModuleNotFoundError:
        print_log.warning(
            "Python Imaging Library (PIL) could not be imported. Using "
            "opencv method for image import. Cannot import exposure time "
            "info from tiff header...please install PIL")
        img = imread(file_path, -1)
    # img = asarray(im)[::-1, 0::] #flip
    img = rot90(rot90(img))
    meta["start_acq"] = datetime.strptime(
        "_".join(basename(file_path).split("_")[:3]), "%Y%m%d_%H%M%S_%f")

    return (img, meta)
예제 #25
0
    def loadImage(self, imageName='8316_128x128.png'):
        im = open(imageName)
        #print im.getbands()
        #print im.mode
        try:
            #image = im.tobytes()
            #ix = im.size
            #iy = im.size[1]
            #image = im.tobytes("raw", "RGBA",0,-1)
            #image = im.tostring()
            ix, iy, image = im.size[0], im.size[1], im.tobytes(
                "raw", "RGBA", 0, -1)
        except (SystemError, ValueError):
            ix, iy, image = im.size[0], im.size[1], im.tobytes(
                "raw", "RGBX", 0, -1)
        except AttributeError:
            ix, iy, image = im.size[0], im.size[1], im.tostring(
                "raw", "RGBX", 0, -1)
        ID = glGenTextures(1)

        glBindTexture(GL_TEXTURE_2D, ID)
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1)

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA,
                     GL_UNSIGNED_BYTE, image)
        return ID
예제 #26
0
def load_array_img(path, is_int=False):
    """
	Load an image-encoded numpy ndarray.
	
	:param path: The path the image is saved at.
	:param is_int: Whether the data are integers (otherwise floats).
	:return: The two-dimensional numpy array encoded by the image.
	"""
    if not isfile(path):
        raise IOError('image array file "{0:s}" not found'.format(path))
    img = open(path)
    if 'dtype' not in img.info:
        warning(
            'png metadata missing or corrupted, cannot determine original data type, using float64'
        )
    datatype = dtype(img.info.get('dtype', 'float64'))
    sz = datatype.itemsize
    if 'padding' not in img.info and sz < 4:
        raise IOError(
            'png metadata missing or corrupted, making assumptions about the shape of the data, this may lead to errors'
        )
    pad_len = int(img.info.get('padding', 0))
    mat_width = img.size[0]
    mat_height = int((img.size[1] * 4 - pad_len / mat_width) / sz)
    mat = frombuffer(img.tobytes(),
                     dtype=datatype,
                     count=mat_width * mat_height)
    mat = mat.reshape((mat_width, mat_height))
    return mat
예제 #27
0
    def __init__(self, master, **kw):
        """
        :param kw: [command, text, theme, font, img, img_bg]
        """
        self.kw = kw
        self.command = lambda *args: print("Working")
        label_kw, my_kw = self.parse_kw()
        self.dark, self.normal, self.light = my_kw["theme"]

        super().__init__(master, **label_kw)
        self.configure(relief="raised")

        if "img" in my_kw:
            image = open(my_kw["img"])
            photo = PhotoImage(image)
            if "img_bg" in my_kw:
                self.configure(image=photo, bg=my_kw["bg"])
            else:
                self.configure(image=photo)
            self.image = photo
        else:
            self.configure(bg=self.normal, fg=self.light)

        self.bind('<Button-1>', lambda *args: self.clicked())
        self.bind('<ButtonRelease-1>', lambda *args: self.unclicked())
예제 #28
0
파일: txt.py 프로젝트: erikhuck/DataClean
def handle():
    """Main method of this module"""

    cohort: str = argv[-1]
    txt_dir: str = '../data/mri/txt-' + cohort
    png_dir: str = '../data/mri/png-' + cohort

    if isdir(txt_dir):
        rmtree(txt_dir)

    mkdir(txt_dir)
    png_ptid_dirs: list = listdir(png_dir)

    for ptid in png_ptid_dirs:
        png_ptid_dir: str = join(png_dir, ptid)
        txt_ptid_dir: str = join(txt_dir, ptid)
        assert not isdir(txt_ptid_dir)
        mkdir(txt_ptid_dir)

        # Ensure the PNG files are read as a sequence trimmed to a consistent sequence length
        png_files: list = trim_sequence(seq=sorted(listdir(png_ptid_dir)))

        for i, png in enumerate(png_files):
            png: str = join(png_ptid_dir, png)
            png: PngImageFile = open(png).convert('L')
            png: ndarray = asarray(png)
            save_img_as_txt(img=png, txt_dir=txt_ptid_dir, txt_idx=i)
예제 #29
0
def loadTexture(string, mipmapping=False):
	h = hash(string)
	if h in texes:
		return texes[h]

	im = open(string)
	
	ix, iy, image = im.size[0], im.size[1], im.convert("RGBA").tostring("raw", "RGBA")
	
	ID = glGenTextures(1)
	glEnable(GL_TEXTURE_2D)
	glBindTexture(GL_TEXTURE_2D, ID)
	glPixelStorei(GL_UNPACK_ALIGNMENT,1)
	if not mipmapping:
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
		glTexImage2D(GL_TEXTURE_2D, 0, 4, ix, iy, 0,GL_RGBA, GL_UNSIGNED_BYTE, image)
	else:
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
		gluBuild2DMipmaps(GL_TEXTURE_2D, 4, ix, iy,GL_RGBA, GL_UNSIGNED_BYTE, image)
	glBindTexture(GL_TEXTURE_2D, 0)
	texes[h] = ID
	return ID
예제 #30
0
    def main(self, dir_path, id_length, database_name):
        print(isdir(join(dir_path, 'in')))
        if not isdir(join(dir_path, 'in')):
            rename_files(dataset_dir=dir_path, id_length=id_length)
            print('Rename Done')

            correct_tree(dataset_path=dir_path)
            print('Tree Corrected')

            crop_to_crown(root_file_path=dir_path)
            print('cropped')

            augment(root_dir_path=dir_path)
            print('augmented')

            correct_histogram(root_dir_path=dir_path)
            print('Histogram Corrected')

        self.file_remove(join('database', database_name))

        for subdir, dirs, files in walk(dir_path):
            if subdir != dir_path:
                for file in files:
                    if 'jpg' in file:
                        img_relative_path = join(subdir, file)
                        image = open(img_relative_path).convert('RGB')
                        features = get_features(image, self.resnet)
                        add_image_features(file.split('.')[0], features, database_name)

        print('Database Created')
예제 #31
0
def standardize_image(image: bytes, crop_params: List) -> bytes:
    raw_image = open(io.BytesIO(image)).convert('RGB')
    cropped_image = _crop_image(crop_params[0], crop_params[1], crop_params[2],
                                raw_image)
    resized_image = _resize_image(cropped_image)
    standard_image = _convert_to_jpeg(resized_image)
    return standard_image
 def loadImage(self, imageName="nehe_wall.bmp"):
     """Load an image from a file using PIL."""
     try:
         from PIL.Image import open
     except ImportError:
         from Image import open
     glActiveTexture(GL_TEXTURE0_ARB)
     return texture.Texture(open(imageName))
예제 #33
0
def rename(img):
    """Rename an image old with new name"""
    ext = splitext(img)[1].lower()
    name = get_date(open(img))
    print(name)
    if name is not None:
        name = name + ext
        return copy(img, name)
예제 #34
0
 def loadImage(self, imageName="nehe_wall.bmp"):
     """Load an image file as a 2D texture using PIL
     """
     try:
         from PIL.Image import open
     except ImportError as err:
         from Image import open
     im = texture.Texture(open(imageName))
     return im
예제 #35
0
파일: io.py 프로젝트: simonsben/doc_master
def load_image(path):
    path = make_path(path)
    if not path.exists():
        raise FileExistsError('Specified file doesn\'t exist')

    image = open(path)
    image = to_greyscale(asarray(image)).copy()

    return image
예제 #36
0
 def exiftaken(self):
     i = open(self.local())
     info = i._getexif()
     if info:
         for tag, value in info.items():
             decoded = TAGS.get(tag, tag)
             if decoded == 'DateTimeOriginal':
                 return datetime.strptime(value, '%Y:%m:%d %H:%M:%S')
     return timezone.now()
예제 #37
0
 def figure_to_array(self, figure):
     from io import BytesIO
     from PIL.Image import open
     from numpy import asarray
     figure_buf = BytesIO()
     figure.savefig(figure_buf, format='jpg')
     figure_buf.seek(0)
     image = asarray(open(figure_buf))
     return image
예제 #38
0
 def loadLightMap(self, imageName="lightmap1.jpg"):
     """Load an image from a file using PIL as a lightmap (greyscale)
     """
     try:
         from PIL.Image import open
     except ImportError:
         from Image import open
     glActiveTextureARB(GL_TEXTURE1)
     return texture.Texture(open(imageName))
예제 #39
0
def loadImage(filename):
    """Load an image file as a 2D texture using PIL"""
    im = open(filename).convert("RGBA")
    ix, iy, image = im.size[0], im.size[1], im.tostring("raw", "RGBA", 0, -1)
    ID = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, ID)
    glPixelStorei(GL_UNPACK_ALIGNMENT,1)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image)
    return ID
 def __getitem__(self, index):
     data = open(os.path.join(self.filedir, self.filelist[index]))
     data = data.convert('RGB')
     if self.transforms:
         data = self.transforms(data)
     meta = self.metadata[self.metadata['Filename'] == self.filelist[index]]
     label = self.label_dict[meta['Label'].values[0]]
     label = int(label)
     return data, label
예제 #41
0
    def __getitem__(self, index):
        new_img = open(self.x_img_path[index])

        if not self.is_grey_scale:
            rgb_img = new("RGB", new_img.size)
            rgb_img.paste(new_img)

        out_img = self.transform(new_img)

        return out_img, self.y_label[index]  # data, target
예제 #42
0
def I2T(File):
	text, im, counter, field= "", open(File), 0, True
	for pixel in list(im.convert("1").getdata()):
		if field: text += "*" if pixel > 127 else " "
		counter += 1
		if counter >= im.size[0]:
			counter = 0
			if field: text += "\n"
			field = not field
	return text
예제 #43
0
 def loadLightMap(self, imageName="lightmap1.jpg"):
     """Load an image from a file using PIL as a lightmap (greyscale)
     """
     try:
         from PIL.Image import open
     except ImportError as err:
         from Image import open
     multitexture.glActiveTextureARB(multitexture.GL_TEXTURE1_ARB)
     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
     return texture.Texture(open(imageName))
 def set_file(self, filetype, instance_button, instance):
     if filetype == 'text':
         self.screen.textfiles.set_item(instance.text[-75:])
         self.current_file.text[0] = instance.text
         self.text.text = "".join(open(instance.text, encoding='utf-8').readlines())
         self.text.cursor = (0, 0)
         self.textfiles_menu.dismiss()
     if filetype == 'hocr':
         self.screen.hocrfiles.set_item(instance.text[-75:])
         self.current_file.hocr[0] = instance.text
         self.interactive_hocr(instance.text)
예제 #45
0
 def testPublishCustomSize(self):
     # set custom image sizes
     changeAllowedSizes(self.portal, [u'foo 23:23'])
     # make sure traversing works as expected
     base = '/'.join(self.folder.getPhysicalPath())
     credentials = self.getCredentials()
     response = self.publish(base + '/foo-image/image_foo', basic=credentials)
     self.assertEqual(response.getStatus(), 200)
     foo = open(StringIO(response.getBody()))
     self.assertEqual(foo.format, 'GIF')
     self.assertEqual(foo.size, (23, 23))
     # make sure the traversal adapter was call in fact
     self.assertEqual(self.counter, 3)
예제 #46
0
def loadImage(imageName):
    im = open(imageName)
    try:
        ix, iy, image = im.size[0], im.size[1], im.tostring("raw", "RGBA", 0, -1)
    except SystemError:
        ix, iy, image = im.size[0], im.size[1], im.tostring("raw", "RGBX", 0, -1)
    ID = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, ID)
    glPixelStorei(GL_UNPACK_ALIGNMENT,4)
    glTexImage2D(
        GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image
    )
    return ID
예제 #47
0
    def loadImage( self, imageName = 'nehe_wall.bmp', convolve=True ):
        """Load an image file as a 2D texture using PIL

        This method combines all of the functionality required to
        load the image with PIL, convert it to a format compatible
        with PyOpenGL, generate the texture ID, and store the image
        data under that texture ID.

        Note: only the ID is returned, no reference to the image object
        or the string data is stored in user space, the data is only
        present within the OpenGL engine after this call exits.
        """
        im = open(imageName)
        try:
            ix, iy, image = im.size[0], im.size[1], im.tostring("raw", "RGBA", 0, -1)
        except SystemError:
            ix, iy, image = im.size[0], im.size[1], im.tostring("raw", "RGBX", 0, -1)
        # generate a texture ID
        ID = glGenTextures(1)
        # make it current
        glBindTexture(GL_TEXTURE_2D, ID)
        glPixelStorei(GL_UNPACK_ALIGNMENT,1)
        # copy the texture into the current texture ID
        if convolve:
            glEnable(GL_CONVOLUTION_2D);
            glConvolutionParameteri(
                GL_CONVOLUTION_2D,
                GL_CONVOLUTION_BORDER_MODE, 
                GL_CONSTANT_BORDER
            )
            assert glGetConvolutionParameteriv( 
                GL_CONVOLUTION_2D,
                GL_CONVOLUTION_BORDER_MODE, 
            ) == GL_CONSTANT_BORDER, glGetConvolutionParameteriv( 
                GL_CONVOLUTION_2D,
                GL_CONVOLUTION_BORDER_MODE, 
            )
            glConvolutionFilter2D(
                GL_CONVOLUTION_2D, GL_RGBA,
                self.FILTER_SIZE, self.FILTER_SIZE,
                GL_RGBA, GL_FLOAT, self. convolutionKernel
            )
            setFilter = glGetConvolutionFilter(
                GL_CONVOLUTION_2D, GL_RGBA, GL_FLOAT 
            )
            #assert setFilter.shape == (4,4)
            #assert setFilter.dtype == self.convolutionKernel.dtype
        glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image)
        glDisable( GL_CONVOLUTION_2D )
        # return the ID for use
        return ID
    def _jpegImage(self):
        """Convert our testimage to jpeg format and return it's data
        """

        from cStringIO import StringIO
        from PIL.Image import open

        img = open(file(join(dirname(tests.__file__), 'plone-logo.png')))
        out = StringIO()
        img.save(out, format='JPEG', quality=75)
        out.seek(0)
        result = out.getvalue()
        out.close()
        return result
예제 #49
0
def read():
    """
    Read face image data from the CBCL database. The matrix's shape is 361 (pixels) x 2429 (faces). 
    
    Step through each subject and each image. Images' sizes are not reduced.  
    
    Return the CBCL faces data matrix. 
    """
    print("Reading CBCL faces database")
    dir = join(dirname(dirname(abspath(__file__))), "datasets", "CBCL_faces", "face")
    V = np.zeros((19 * 19, 2429))
    for image in range(2429):
        im = open(join(dir, "face0%s.pgm" % str(image + 1).zfill(4)))
        V[:, image] = np.asarray(im).flatten()
    return V
	def runSegmentation(self, imgPath):
		PILImage = open(imgPath)
		self.img = PILImage
		self.wImg , self.hImg = PILImage.size
		self.horizontalTop = self.wImg
		self.verticalTop = self.hImg
		i = 0
		while True:
			segment = self.getNexSegment()
			#Romper ciclo hasta que se reinicie la coordenada de recorte
			if(segment.xPositionClipper == 0 and segment.yPositionClipper == 0 and i != 0):
				break
			segment.PILImage.save('img/segments/cutout'+str(i)+'.jpg')
			i+=1
		return i+1
    def reloadGraph(self, im):
        im = open(self.graphFile)
        try:
            ix, iy, image = im.size[0], im.size[1], \
                    im.tostring("raw", "RGBA", 0, -1)
        except SystemError:
            ix, iy, image = im.size[0], im.size[1], \
                    im.tostring("raw", "RGBX", 0, -1)
        
        # Reload network graph.
        glBindTexture(GL_TEXTURE_2D, self.graphTex)
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1)

        glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0,
                     GL_RGBA, GL_UNSIGNED_BYTE, image)
예제 #52
0
 def testPublishCustomSize(self):
     data = getData('image.gif')
     self.folder.invokeFactory('Image', id='foo', image=data)
     # set custom image sizes
     iprops = self.portal.portal_properties.imaging_properties
     iprops.manage_changeProperties(allowed_sizes=['foo 23:23'])
     # make sure traversing works as expected
     base = '/'.join(self.folder.getPhysicalPath())
     credentials = self.getCredentials()
     response = self.publish(base + '/foo/image_foo', basic=credentials)
     self.assertEqual(response.getStatus(), 200)
     foo = open(StringIO(response.getBody()))
     self.assertEqual(foo.format, 'PNG')
     self.assertEqual(foo.size, (23, 23))
     # make sure the traversal adapter was call in fact
     self.assertEqual(self.counter, 3)
예제 #53
0
def read():
    """
    Read face image data from the CBCL database. The matrix's shape is 361 (pixels) x 2429 (faces). 
    
    Step through each subject and each image. Images' sizes are not reduced.  
    
    Return the CBCL faces data matrix. 
    """
    print "Reading CBCL faces database ..."
    dir = dirname(dirname(abspath(__file__)))+ sep + 'datasets' + sep + 'CBCL_faces' + sep + 'face'
    V = np.matrix(np.zeros((19 * 19, 2429)))
    for image in xrange(2429):
        im = open(dir + sep + "face0" + str(image + 1).zfill(4) + ".pgm")
        V[:, image] = np.mat(np.asarray(im).flatten()).T      
    print "... Finished."
    return V
예제 #54
0
    def segment_entry_image(self, url_image, url_output):
        img = open(url_image)

        width_image, height_image = img.size
        trajectory = get_circular_trajectory(width_image, height_image)
        segmenter = get_rectangular_segmenter(img, trajectory)

        i = 0
        image = segmenter.get_current_segment()
        image.pil_image.save(url_output+'cutout' + str(i) + '.jpg')

        i += 1
        while (segmenter.has_next_segment()):
            image = segmenter.get_next_segment()
            image.pil_image.save(url_output+'cutout' + str(i) + '.jpg')
            i += 1
        return i
예제 #55
0
 def testPublishCustomSize(self):
     data = self.getImage()
     folder = self.folder
     folder.invokeFactory('Image', id='foo', image=data)
     # set custom image sizes
     settings = getSettings()
     settings.allowed_sizes = [u'foo 23:23']
     # make sure traversing works as expected
     base = '/'.join(folder.getPhysicalPath())
     credentials = self.getCredentials()
     response = self.publish(base + '/foo/image_foo', basic=credentials)
     self.assertEqual(response.getStatus(), 200)
     foo = open(StringIO(response.getBody()))
     self.assertEqual(foo.format, 'PNG')
     self.assertEqual(foo.size, (23, 23))
     # make sure the traversal adapter was call in fact
     self.assertEqual(self.counter, 3)
예제 #56
0
    def loadImages( self, imageName = "nehe_crate.bmp" ):
        """Load an image from a file using PIL,
        produces 3 textures to demo filter types.

        Converts the paletted image to RGB format.
        """
        im = open(imageName)
        try:
            ## Note the conversion to RGB the crate bitmap is paletted!
            im = im.convert( 'RGB')
            ix, iy, image = im.size[0], im.size[1], im.tostring("raw", "RGBA", 0, -1)
        except SystemError:
            ix, iy, image = im.size[0], im.size[1], im.tostring("raw", "RGBX", 0, -1)
        assert ix*iy*4 == len(image), """Image size != expected array size"""
        IDs = []
        # a Nearest-filtered texture...
        ID = glGenTextures(1)
        IDs.append( ID )
        glBindTexture(GL_TEXTURE_2D, ID)
        glPixelStorei(GL_UNPACK_ALIGNMENT,1)
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image)
        # linear-filtered
        ID = glGenTextures(1)
        IDs.append( ID )
        glBindTexture(GL_TEXTURE_2D, ID)
        glPixelStorei(GL_UNPACK_ALIGNMENT,1)
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR)
        glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image)
        # linear + mip-mapping
        ID = glGenTextures(1)
        IDs.append( ID )
        glBindTexture(GL_TEXTURE_2D, ID)
        glPixelStorei(GL_UNPACK_ALIGNMENT,1)
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST)
        print 'doing mip-maps, fails on RedHat Linux'
        gluBuild2DMipmaps(
            GL_TEXTURE_2D, 
            GL_RGBA, ix, iy, GL_RGBA, GL_UNSIGNED_BYTE, image
        )
        print 'finished mip-mapped'
        return IDs
예제 #57
0
파일: orl_images.py 프로젝트: Keita1/nimfa
def read():
    """
    Read face image data from the ORL database. The matrix's shape is 2576 (pixels) x 400 (faces). 
    
    Step through each subject and each image. Reduce the size of the images by a factor of 0.5. 
    
    Return the ORL faces data matrix. 
    """
    print("Reading ORL faces database")
    dir = join(dirname(dirname(abspath(__file__))), 'datasets', 'ORL_faces', 's')
    V = np.matrix(np.zeros((46 * 56, 400)))
    for subject in range(40):
        for image in range(10):
            im = open(join(dir + str(subject + 1), str(image + 1) + ".pgm"))
            # reduce the size of the image
            im = im.resize((46, 56))
            V[:, image * subject + image] = np.mat(np.asarray(im).flatten()).T
    return V
    def __init__(self, length=4):
        self.length = length
        self.graphs = []
        for i in range(length - 1):
            self.graphs.append(visgraph.Graph())
        multi = visgraph.MultiGraph()
        for i in range(3):
            multi.addGraph(visgraph.Graph())
        self.graphs.append(multi)

        self.graphFile = "graph.png"

        # Open graph.png.
        self.im = open(self.graphFile)

        self.nodes = ["---"]
        self.nodeData = ["Select a node."]
        self.nodeCount = 0
예제 #59
0
  def __loadimage__( self, filepath='/home/lorin/projects/ge/art/alien.png' ):
    """
    """
#    print filepath
    img = open( filepath )
    img_data =  img.tostring("raw", "RGBA", 0, -1) 
    #numpy.array( list( img.getdata() ), numpy.int8)
    texture_id = glGenTextures(1)
    glPixelStorei( GL_UNPACK_ALIGNMENT, 1 )
    glBindTexture(GL_TEXTURE_2D, texture_id)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 
                  img.size[0], 
                  img.size[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, img_data )
    self._textures[filepath] = texture_id
    return texture_id
    def InitGL(self):
        # Set viewing projection
        glMatrixMode(GL_PROJECTION)

        # Use 2-dimensional orthographic projection.
        gluOrtho2D(-1.0, 1.0, -1.0, 1.0)

        # Enable depth testing. This isn't really necessary, but doesn't hurt.
        glEnable(GL_DEPTH_TEST)

        # Open graph.png.
        self.im = open(self.graphFile)

        # Generate texture for network graph.
        self.graphTex = self.loadImage(self.im)
        
        #glEnable(GL_TEXTURE_2D)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)