Menu
  • HOME
  • TAGS

Get binary image data from PIL.Image?

python,python-imaging-library

PIL uses a lazy opening mechanism, in which the file contents are only read when needed. FOr doing that, it probably keeps the file reference in some internal (private) attribute. Even if this attribute is accessible, it certainly is not exposed as part of the oficial PIL API - and...

How do I fix my error with PIL and numpy images

python,image,python-3.x,numpy,python-imaging-library

The image_shuffle function is wrong. It should be: for row in range(original_image.size[0]): for col in range(original_image.size[1]): r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) original_image.putpixel((row, col), (r,g,b)) You want to have color values starting from 0 unless you don't want to get all the possible colors....

PIL posterize- fix green pixels

python,python-imaging-library

You're using bisect_left almost correctly... almost. If you read the documentation, you'll notice how bisect takes lo and hi parameters, which are set to 0 and len(arr) respectively. To work around IndexError, you add -1 to the result. But this will map results that should be 0 to len-1, since...

Convert an images pixel value from rgb to grayscale manually python PIL?

python,python-imaging-library,grayscale

I found that i could just build another image: import sys import os import glob import numpy from PIL import Image def tau_gamma_correct(pixel_channel): pixel_channel = pixel_channel**(1/2.2) return pixel_channel #@param: rgb #@result: returns grayscale value def gleam(rgb): #convert rgb tuple to list rgblist = list(rgb) #gamma correct each rgb channel rgblist[0]...

PIL attribute error

python,python-2.7,python-imaging-library

You can't subscript the image object directly, you must use the load method to create an access object. im = Image.open(imageData) buffer1 = im.load() print buffer1[1,1] ...

Pasting image from clipboard to MS Word has wrong aspect ratio

winapi,python-3.x,python-imaging-library,ctypes

The resolution of a windows bitmap is defined by the biXPelsPerMeter and biYPelsPerMeter members of the `BITMAPINFOHEADER' structure. The Python Imaging Library (PIL) writes the resolution as 1 pixel per meter in both directions (line 225 of BmpImagePlugin.py). Thus Word thinks the bitmap is hundreds of metres in size and...

PIL/Pillow IOError: cannot identify image file u'xxxx.jpg' (Windows only)

python,windows,python-imaging-library

You are copying images into a file opened in text mode: f = open(image_name, 'w') f.write(urllib2.urlopen(image).read()) On Windows this means that any 0A (newline) bytes are translated to 0D 0A byte sequences (carriage return, newline), as that is the Windows line separator. Open your files in binary mode: f =...

Python XMP Toolkit is too strict (“Unrecognized TIFF prefix”) when trying to read image metadata

python,image,python-imaging-library,exif,xmp

This doesn't seem completely ideal, but I've found a solution that may be 'good enough' for me. Here is some code inspired by the answers in this question. import libxmp def parse_xmp(path): data = libxmp.utils.file_to_dict(path) if not data: data = dirty_parse_xmp(path) return data def dirty_parse_xmp(path): # Find the XMP data...

How can I read jpeg file binary (without decoding) properly and save it?

python,pandas,jpeg,python-imaging-library

You can use mahotas which is a popular library to reading/quantifying image. Install it via terminal pip install mahotas. import mahotas as mh import numpy as np original_img = np.array(mh.imread('figure1.jpg'), dtype=np.float64) / 255 # check dimension, RGB original_img.shape Out[13]: (1536, 2048, 3) width, height, depth = original_img.shape # reshape image_flattened...

Python PIL: how understand hexadecimal code in ?

python,python-imaging-library

You can't "translate this number properly", because all that number means is where in memory Pillow is storing the object, and there's nothing useful you can translate that to. If you're trying to get information out of an object in Python, you do that by accessing its attributes and methods....

Plot gradients using PIL in Python

python,image,python-imaging-library

The code depends on how you want the gradient to look. You could make it a rectangular gradient which would look like this: Or you could make it a round gradient like this: This would be the code for the round gradient: import Image import math imgsize = (250, 250)...

Calculate Euclidean distance for each item in a list

python,python-imaging-library,pixels,pillow,euclidean-distance

Try this: colors = im.getdata() #all pixel values # initialize lists for dark and light pixels darkList=[] lightList=[] # set counter for dark and light pixels dark = 0 light = 0 for item in colors: # iterate over each tuple if sqrt((item[0]-255)**2 + (item[1]-255)**2) < 128: # See if...

Generate random colors (RGB)

python,random,python-imaging-library

Here: def random_color(): rgbl=[255,0,0] random.shuffle(rgbl) return tuple(rgbl) The result is either red, green or blue. The method is not applicable to other sets of colors though, where you'd have to build a list of all the colors you want to choose from and then use random.choice to pick one at...

Image not saving after updating pixel color in PIL

python,python-2.7,python-imaging-library

You need to copy the modified pixel value back into the pixel access object. Eg, if px[x, y] == (150, 150, 150): px[x, y] = (0, 0, 255) There's an example in the old PIL docs for Image.load(). If you're modifying a lot of pixels, you may wish to use...

Is there a cleaner way to rotate smartphone images uploaded via flask before pushing to S3?

python,heroku,amazon-s3,flask,python-imaging-library

For what it is worth, Pillow supports a number of other inputs than a file name - including bytearray, buffer, and file-like object. The third is most probably what you are looking for, as anything loaded out of request.files is just a FileStorage file-like object. That simplifies the load-and-transform code...

Simple way to resize large number of image files

shell,image-processing,python-imaging-library

I would use GNU Parallel, like this to make the most of all those cores: find . -name \*.jpg | parallel -j 16 convert {} -resize 256x256 {} If you had fewer files, you could do it like this, but the commandline would be too long for 45,000 files: parallel...

How can I determine the length of a multi-page TIFF using Python Image Library (PIL)?

python,image-processing,python-imaging-library,tiff

If you can wait until 1st July 2015, the next release of Pillow (the PIL fork) will allow you to check this using n_frames. If you can't wait until then, you can copy that implementation,patch your own version, or use the latest dev version. More info here: https://github.com/python-pillow/Pillow/pull/1261...

How can I create a PNG image file from a list of pixel values in Python?

python,image,list,file,python-imaging-library

Quick fix First, you need to have your pixel tuples in a single un-nested list: pixels_out = [] for row in pixels: for tup in row: pixels_out.append(tup) Next, make a new image object, using properties of the input image, and put the data into it: image_out = Image.new(image.mode,image.size) image_out.putdata(pixels_out) Finally,...

How to create thumbnails using opencv-python?

python,opencv,image-processing,python-imaging-library

You can use cv2.resize . Documentation here: http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html#resize In your case, assuming the input image im is a numpy array: maxsize = (1024,1024) imRes = cv2.resize(im,maxsize,interpolation=cv2.CV_INTER_AREA) There are different types of interpolation available (INTER_CUBIC, INTER_NEAREST, INTER_AREA,...) but according to the documentation if you need to shrink the image, you should...

Migration issue with custom model field

python,django,python-imaging-library,sorl-thumbnail,django-migrations

For anyone encountering this issue, here is the solution: def deconstruct(self): # Use ImageField as path, as the deconstruc() will return ImageWithThumbnailsField field_class = "django.db.models.fields.files.ImageField" name, path, args, kwargs = super(BaseThumbnailField, self).deconstruct() return name, field_class, args, kwargs ...

Python PIL/Pillow - Pad image to desired size (eg. A4)

python,image,python-imaging-library,pillow

from PIL import Image im = Image.open(my_image_file) a4im = Image.new('RGB', (595, 842), # A4 at 72dpi (255, 255, 255)) # White a4im.paste(im, im.getbbox()) # Not centered, top-left corner a4im.save(outputfile, 'PDF', quality=100) This is taking as hypothesis that my_image_file has the same resolution, 72dpi....

Combine several images horizontally with Python

python-2.7,python-imaging-library,paste

You can do something like this: import sys from PIL import Image images = map(Image.open, ['Test1.jpg', 'Test2.jpg', 'Test3.jpg']) widths, heights = zip(*(i.size for i in images)) total_width = sum(widths) max_height = max(heights) new_im = Image.new('RGB', (total_width, max_height)) x_offset = 0 for im in images: new_im.paste(im, (x_offset,0)) x_offset += im.size[0] new_im.save('test.jpg')...

Error installing PIL library for Python

python,xcode,python-imaging-library,failed-installation

Did you uninstall PIL first? Try: pip uninstall pil pip uninstall pillow brew install libtiff libjpeg webp little-cms2 pip install pillow See http://pillow.readthedocs.org/installation.html for more information....

Memory Growth Though Overwritten

python,memory,garbage-collection,python-imaging-library

The problem is not a memory leak, it's the expand argument. From the pillow docs (emphasis mine): expand – Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. You can add print(rotation.size) size in the loop to see this....

StringIO Cannot Identify Image File Error

python,image,python-imaging-library,pillow,stringio

I just installed Pillow on a nearly fresh Ubuntu 14.04, using pip install Pillow. The installation was successful. However, take a look on the installation summary: -------------------------------------------------------------------- PIL SETUP SUMMARY -------------------------------------------------------------------- version Pillow 2.8.2 platform linux2 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] -------------------------------------------------------------------- *** TKINTER support not available...

Python PIL - AttributeError: 'NoneType' object has no attribute 'save'

python,border,python-imaging-library,crop,trim

The Python principle of EAFP could apply here. Basically you should have your code attempt to execute and then catch an AttributeError, telling it to skip that image. Like this: def CropImages(): global FOLDER for i in range(1, len(os.listdir(FOLDER))+1): image = FOLDER + "\\" + str(i) + ".jpg" img =...

Python scp copy images from image_urls to server

python,python-imaging-library,urllib,scp

The problem is that image_file is not a path (string), it's an object. Your os.system call is building up a string that expects a path. You need to write the file to disk (perhaps using the tempfile module) before you can pass it to scp in this manner. In fact,...

Converting Array into Image (tif) in Python using Pillow

python,arrays,python-imaging-library,pillow

image_data is a tuple of 4 numpy arrays, each (probably) of shape (H, W). You need image_data to be a single array of shape (H, W, 4). Therefore, use np.dstack to combine the channels. At least one of your arrays has dtype int32. But to use it as an 8-bit...

EXIF python PIL return emtpy dictionary

python,python-2.7,python-imaging-library,exif

As an alternative to using _getexif() we can use subprocess.chck_output to run identify and parse the output into a dict: from subprocess import check_output c = check_output("identify -verbose img.jpg".split()) d = {} print(c) for line in c.splitlines()[:-1]: spl = line.split(":",1) k, v = spl d[k.lstrip()] = v.strip() print(d) {'Blue': '',...

Tkinter being fickle with pictures, some are blank, others are not

python,python-2.7,tkinter,python-imaging-library

The following code works for me in Python 3, displaying either image just fine. from tkinter import * from PIL import Image,ImageTk import urllib.request import io url1 = 'https://lh3.googleusercontent.com/-bnh6_0GlqbA/VUKUsl1Pp9I/AAAAAAACGoM/Vx9yu1QGIKQ/s650/Sunset.png' url2 = 'https://lh3.googleusercontent.com/-_J57qf7Y9yI/VUPaEaMbp9I/AAAAAAACGuM/3f4551Kcd0I/s650/UpsideDawn.png' window = Tk() imagebytes = urllib.request.urlopen(url1).read() imagedata = io.BytesIO(imagebytes) imagePIL = Image.open(imagedata) imageready =...

Strange Pillow exception while saving cropped image

python,python-2.7,python-imaging-library

Basically, the problem originated on a conflicting PIL installation in one of the app servers. It was hard to find since they were hiding behind a load balancer, so the error would pop out sometimes When we issued pip freeze on the console, we found out that in one of...

Cannot construct tkinter.PhotoImage from PIL Image

python,tkinter,resize,python-imaging-library,resize-image

The PhotoImage class from tkinter takes a filename as an argument, and as it cannot convert the image into a string, it complains. Instead, use the PhotoImage class from the PIL.ImageTk module. This works for me: from tkinter import * from PIL import ImageTk, Image def image_resize(imageFile): width = 500...

How to gauss-filter (blur) a floating point numpy array

python,numpy,filtering,python-imaging-library

If you have a two-dimensional numpy array a, you can use a Gaussian filter on it directly without using Pillow to convert it to an image first. scipy has a function gaussian_filter that does the same. from scipy.ndimage.filters import gaussian_filter blurred = gaussian_filter(a, sigma=7) ...

opening a jpg file in python

python,image-processing,python-imaging-library

Instead of: im = Image.open('withmed.jpg',0) try: im = Image.open('withmed.jpg') If that doesn't work, put print(im) afterwards and tell us what it says. ...

what is the valid format for a tiff image in python

image,python-3.x,image-processing,python-imaging-library,tiff

Are you required to exactly use PIL? Otherwise, have you tried using it's open source clone called Pillow? Refer to https://python-pillow.github.io/ Pillow seems to be able to directly save image data in tiff file format. Try something like: img = Image() # any editing of 'img' img.save( 'mytiff.tif' ) Otherwise,...

With Python`s PIL, how to set DPI before loading an image?

python,image-processing,python-imaging-library,pythonmagick

AFAIK, while it can contain embedded bitmaps and a preview thumbnail, EPS is a vector-based format. It only makes sense to set DPI if you are generating output in a bitmap format. You are right - I am trying to generate a bitmap picture from the eps. But opening (parsing?)...

Using PIL (Python Image Library) to detect image on screen

python,python-imaging-library

PIL is the wrong tool for this job. Instead you should look into openCV (open source computer vision), which has fantastic python bindings. Here is a link to an example (in C but should be easy to redo with the python bindings) that does what you are looking for, but...

Comparing 2 images/pictures by using PIL, some doesn't work

python,image,python-imaging-library

from PIL import Image from PIL import ImageChops from PIL import ImageDraw im1 = Image.open('a.jpg') im2 = Image.open('aa.jpg') diff = ImageChops.difference(im2, im1).getbbox() print diff draw = ImageDraw.Draw(im2) draw.rectangle(diff, outline = (0,255,0)) print help(draw.rectangle) im2 = im2.convert('RGB') im2.save('aaa.jpg') Help on method rectangle in module PIL.ImageDraw: rectangle(self, xy, fill=None, outline=None) method of...

Image not Found using PIL and Urllib to retrieve URL

python,python-2.7,tkinter,python-imaging-library,urllib

For me the following code works. Please check if you do same: import urllib, io from Tkinter import * from PIL import Image, ImageTk root = Tk() fd = urllib.urlopen("http://www.google.com/images/srpr/logo11w.png") imgFile = io.BytesIO(fd.read()) im = ImageTk.PhotoImage(Image.open(imgFile)) # <-- here image = Label(root, image = im) image.grid(row = 7, column =...

how to identify webp image type with python

python,image,python-imaging-library,webp

The imghdr module doesn't yet support webp image detection; it is to be added to Python 3.5. Adding it in on older Python versions is easy enough: import imghdr try: imghdr.test_webp except AttributeError: # add in webp test, see http://bugs.python.org/issue20197 def test_webp(h, f): if h.startswith(b'RIFF') and h[8:12] == b'WEBP': return...

Python PIL - open image from file object: File not open for reading

python,python-imaging-library,pillow

You opened the file for writing, not reading. You'd have to use a dual mode, and first rewind the file pointer: with open('myimage.png', 'w+b') as imgfile: imgfile.write(decodestring(base64_image)) imgfile.seek(0) f = Image.open(imgfile) Here w+ means writing and reading, see the open() documentation: '+' open a disk file for updating (reading and...

PIL: overlaying images with different dimensions and aspect ratios

python,python-imaging-library

A solution upfront. Background image width/height/ratio: 300 / 375 / 0.800 Foreground image width/height/ratio: 400 / 464 / 0.862 Overlay from PIL import Image imbg = Image.open("bg.png") imfg = Image.open("fg.png") imbg_width, imbg_height = imbg.size imfg_resized = imfg.resize((imbg_width, imbg_height), Image.LANCZOS) imbg.paste(imfg_resized, None, imfg_resized) imbg.save("overlay.png") Discussion The most important information you have...

Simplest .jpg Display in Python 3

python-3.x,jpeg,python-imaging-library

Try Pillow, it should work on python 2 and 3: http://python-pillow.github.io...

PIL Image.save results in incorrect pixel mapping

python,python-imaging-library

"Shouldn't these values be identical?" No. JPEG is a lossy format - which means that at save time, the Jpeg encoding library can change the actual values in the pixels - which can vary due to many factors - desired jpeg quality being one of them. If you save the...

Save pixel data in txt format in PIL

python,python-imaging-library,getpixel

Just create an file writer object and write the value of variable pixel to that. from PIL import Image im=Image.open("thresh.jpg") fil = open('file', 'w') pixel = im.load() row,column=im.size for y in range(column) for x in range(row) pixel=pix[x,y] fil.write(str(pixel)+'\n') fil.close() ...

working with tiff files in python

python,image-processing,tkinter,python-imaging-library,tiff

The TIFF file format is very versatile. Yes, it can store pixels in float format, it can even store complex-valued pixels. In general. On the other hand, as far as I know, PIL is not directly able to handle float-valued image data. Even more, saving image data with float-valued pixels...

How to save a 3 channel numpy array as image

python,numpy,python-imaging-library

The @Dietrich answer is valid, however in some cases it will flip the image. Since the transpose operator reverses the index, if the image is stored in RGB x rows x cols the transpose operator will yield cols x rows x RGB (which is the rotated image and not the...

attaching an image (or object) from memory to an email in python

python,python-imaging-library,email-attachments

MIMEImage says that the first argument is just "a string containing the raw image data", so you don't have to open() then .read() it from a file. If you're making it in PIL and there isn't a way to serialize it directly (there might not be, I can't recall), you...

Load 64-bit raw image file in python

python,numpy,scipy,python-imaging-library

In a nutshell: import numpy as np import matplotlib.pyplot as plt fname = 'Downloads/image.bdat' with open(fname, 'r') as infile: infile.seek(4) data = np.fromfile(infile, dtype='>f8').reshape(1024, 256) fig, ax = plt.subplots() im = ax.imshow(data, cmap='gray') ax.set(xticks=[], yticks=[]) fig.colorbar(im) fig.savefig('figure_1.png', bbox_inches='tight') plt.show() Let me back up and explain what's going on. First off,...

Import pillow without installing

python,python-3.x,python-imaging-library,pillow

One solution is bundle PIL in with the script in .egg form. Then, you can import PIL directly from the .egg instead of having to install it: How to create Python egg file The basic process is as follows: How to create egg: Edit PIL's setup.py to include from setuptools...

Create an ICO working on XP with python from a PNG or JPG

python,python-2.7,windows-xp,python-imaging-library,ico

It is not working with Pillow because ICO is saved PNG format, see answer here https://github.com/python-pillow/Pillow/issues/1102 It is working properly with PythonMagick....

Opening Images as Arrays

python,arrays,image,numpy,python-imaging-library

Have you tried the imread function from matplotlib? from matplotlib.image import imread image = imread(image_path) Returns a numpy array and works fine for me (python 3.4). ...

What does the 3rd tuple value stand for in Pillow.Image.tile?

python,image,python-imaging-library,pillow

From Using PIL on Large Images: The third item is the offset from the start of the file to the data for that tile. the data for that tile is 106 bytes into the raw stream. The tile itself is 80 * 242 * 4 (RGBA) == 77440 bytes, so...

“Blending out” noise in images?

python,image,python-imaging-library

Check out MedianFilter in the ImageFilter module. corrected_image = original_image.filter(ImageFilter.MedianFilter(7)) You'll probably want to adjust the filter size. (I've set it to 7 here.)...

Swap R and B color channel values in a directory of images? Python

python,colors,python-imaging-library,image-manipulation

import os from PIL import Image dirPath = r"D:\Fraps\Movies\Screens" dirList = os.listdir(dirPath) outPath = r"D:\Fraps\Movies\Screens\Output" for (dirname, dirs, files) in os.walk(dirPath): for filename in files: if filename.endswith('.png'): print("Opening:"+filename) thefile = os.path.join(dirname,filename) im = Image.open(thefile) #im.load() width, height = im.size im_rgb = im.convert('RGB') for x in range(0, width): for y in...

Can't run an infinite thread with Tkinter

python,multithreading,tkinter,python-imaging-library

In threading.Thread(target=mi_thread()) you are actually running your function. You need to remove the parentheses and pass the function reference only. ie: threading.Thread(target = mi_thread) ...

Downscaling part of image in Python

python,image-processing,numpy,resize,python-imaging-library

There are several problems with your code. Let's tackle the issues one at a time: Issue #1 - (x,y) are useless in your shrink definition I see where you're going with (x,y). You're using this to traverse over each of the larger blocks, summing all of the pixels and dividing...

Can a numpy array be compared to an integer?

python,arrays,numpy,python-imaging-library,linear

It does pretty much what you'd expect: it tests the array img to see if it's greater than 0. But since it's a NumPy array, this is an elementwise comparison: each element is compared to 0. This creates an array of Booleans with the result of the comparison for each...

Create a COLOR image in Python from Matlab data

python,image,matlab,png,python-imaging-library

The img you have has only one channel (grayscale), so what you need is pseudo color visualization. see http://matplotlib.org/users/image_tutorial.html so the code in your for-loop might look like: imgplot = plt.imshow(img) imgplot.set_cmap('spectral') #save the plot with savefig() http://matplotlib.org/api/pyplot_api.html ...

Some PIL.ImageFile attributes like LOAD_TRUNCATED_IMAGES are missed

python,python-imaging-library,intel-edison

The LOAD_TRUNCATED_IMAGES option isn't available in PIL. It was introduced into Pillow, a fork of PIL. (It was added in Pillow 2.0.0.) The last PIL release was five years ago, but Pillow is a maintained fork of PIL. Remove PIL first then install Pillow: pip install pillow...

Error importing PIL when using cx_freeze

python,python-3.x,python-imaging-library,cx-freeze

Edit: I'm glad this solution worked for you! I'll move it here from the comments in case it can help anyone else. Solution: I found a similar error on StackOverflow, and the OP seemed to have found a solution to his own problem. He said that he incorrectly used pip...

Difference between from PIL import Image and import Image

python,python-imaging-library,homebrew,macports,pillow

If you are using PIL, you might be able to use import Image. If you are using Pillow, you must use from PIL import Image. This is by design....

Sending an image in python without saving it

python,image,sockets,pygame,python-imaging-library

You can get the raw image's data with Image.tobytes() and rebuild it from raw data with Image.frombytes(), cf http://pillow.readthedocs.org/en/latest/reference/Image.html#PIL.Image.Image.tobytes and http://pillow.readthedocs.org/en/latest/reference/Image.html#PIL.Image.Image.fromstring Pickle is a notoriously unsafe protocol FWIW so better to stick with raw data. Note that these are features from version 2.x of the Pillow fork of PIL. If...

RGB to HSV Python, change Hue continuously

python,python-imaging-library,rgb,hsv

Use colorsys.hsv_to_rgb to convert the (H,S,V) tuple back to RGB: import os import colorsys import Image def hueChange(img, hue): # It's better to raise an exception than silently return None if img is not # an Image. img.load() r, g, b = img.split() r_data = [] g_data = [] b_data...

How to force Pillow to resize an image to an arbitrary size?

python,image-processing,python-imaging-library

The problem you are getting there is that the resize method returns a new image object, you are not storing anywhere. The original image im is the same that has been loaded. Check the examples on this interactive session: >>> from PIL import Image >>> img = Image.open("image.jpg") >>> img.size...

Resizing images in Python 3.4

python,image,python-imaging-library

You should use Pillow instead. This is a fork of PIL and it's maintained with support for Python 3.x.

Using PIL or pillow to draw an image and display it with TKinter

python,tkinter,python-imaging-library,pillow,tkinter-canvas

Your image is likely getting garbage collected. You need to save a persistent reference to the image.

Using PIL to create thumbnails results in TextEdit Document extension

python,python-imaging-library

This is most likely happening because you aren't saving with a filename extension. Most modern operating systems use file extensions to determine which program should open a file. Since you called: >>> im.save("cherngloong_thumbnail", "PNG") >>> im.save("cherngloong_thumbnail1", "JPEG") the encoding is PNG/JPG, but the extension is not. Also, for why it...

Is it possible read pixels from a jpeg file determenistically across all platforms?

python,c,opencv,jpeg,python-imaging-library

In practice, no. Pixels may differ between different versions of the same library, or even the same version of the same library between platforms. In theory, you will get the same pixels values if you use the exact same algorithm/software on all platforms you need to support. But I think...

Getting started with Python OCR on windows?

python,python-imaging-library,anaconda,python-tesseract,pytesser

The document you point to says to use from PIL import Image except you use import Image and so the interpreter properly says: ImportError: No module named Image It looks as if you reordered the lines from PIL import Image from pytesser import * and that pytesser has a improperly...

cannot use imageQt to cast Image to QImage

python,pyqt4,python-imaging-library

The ImageQt module contains a subclass of QImage, which it imports from PyQt, not PySide. In order to get ImageQt to use PySide, you could try a little hack, like this: import sys from PySide import QtGui sys.modules['PyQt4.QtGui'] = QtGui # or if you have PyQt5 installed, you might need...

Updating Tkinter Label with an Image

python,tkinter,python-imaging-library

Well, I think that the reason is self.show which is None when you press the button. This is because this line: self.show = Label(self.root, image = self.mask).pack(side = "left") should be: self.show = Label(self.root, image = self.mask) self.show.pack(side = "left") This happens, because pack, grid etc. return None....

Install PIL without pypi

python,python-imaging-library,restriction,pillow

If you cannot access it in your school there are several ways you can install it. One way would be installing the needed package on your home computer (when windows type in 'pip install [pckg-name]') you will find that package in your python folder->Lib->site-packages just copy it on some usb...

Using Python to Resize Images when Greater than 1280 on either side

python,python-imaging-library,pillow

You can do it via PIL, something like this: import Image MAX_SIZE = 1280 image = Image.open(image_path) original_size = max(image.size[0], image.size[1]) if original_size >= MAX_SIZE: resized_file = open(image_path.split('.')[0] + '_resized.jpg', "w") if (image.size[0] > image.size[1]): resized_width = MAX_SIZE resized_height = int(round((MAX_SIZE/float(image.size[0]))*image.size[1])) else: resized_height = MAX_SIZE resized_width = int(round((MAX_SIZE/float(image.size[1]))*image.size[0])) image =...

IOError: cannot identify image file

python-imaging-library

I don't know what the problem is with PIL 1.1.6 but I just tested it with the latest Pillow 2.4.0 and this worked: >>> from PIL import Image >>> im = Image.open("8.png") >>> im.show() PIL in unmaintained and Pillow is an actively maintained and developed fork. To use Pillow, first...

Convert image to a digital matrix using python

python,arrays,numpy,python-imaging-library

Because it is a color image. The third dimension is color. thus r = arr[:,:,0] g = arr[:,:,1] b = arr[:,:,2] if PIL opens the image as RGB. This means a red pixel at point (x,y) would be [255, 0, 0], and a white pixel [255, 255, 255]....

How can I equalise intensity for a set of images?

python,python-imaging-library

I find this to be a particularly intriguing problem. However, it has been clumsily posed, so I've suggested that Matt improve the question with some edits. Meanwhile, a few observations. My first thoughts were that perhaps the mismatch was a result of residual color differences in the sub-images, hence my...

Resize url image using urllib and pil

python,python-2.7,io,python-imaging-library,urllib

Pass im_small to PhotoImage instead of Image.open. fd = urllib.urlretrieve("http://images.intellicast.com/WxImages/Radar/den.gif", "den.gif") im1 = Image.open("den.gif") im_small = im1.resize((200, 200), Image.ANTIALIAS) im = ImageTk.PhotoImage(im_small) image = Label(root, image = im, bd =2) image.grid(row = 8, column = 0, columnspan = 2, padx = 20, pady = 30) ...

PIL import png pixels as single value instead of 3 values vector

python,image,png,python-imaging-library

The reason of such result (value 153 in [0,0]) is that image mode is set to P (8-bit pixels, mapped to any other mode using a colour palette). If You want to set different mode (e.g. RGB) You can do it before invoking method load(). Here is an example of...

Creating image through input pixel values with the Python Imaging Library (PIL)

python,python-imaging-library

The format string should be arranged like: "RGBRGBRGBRGB..." Where R is a single character indicating the red value of a particular pixel, and the same for G and B. "But 255 is three characters long, how can I turn that into a single character?" you ask. Use chr to convert...

Python Imaging Library fails to grab whole screen

python,image,python-2.7,python-imaging-library

I was having this problem too earlier today. The script would only capture pixels 0,0 - 1536,864. I recently switched to windows 8 and noticed that some programs seemed to be displayed at the incorrect resolution. After some searching I found a fix. Go to your python directory (c:/python27/ for...

How to Manipulate TIFF header values in Python (PIL)?

python,python-imaging-library,tiff

For anyone interested...I gave up on PIL working for this. I'm convinced that there's a bug in there and I don't have the time to fix it. If you monkey with any of the headers then it blows away ALL of the header information on Image.save(). Instead I installed libtiff...

Get Binary Representation of PIL Image Without Saving

python,node.js,sockets,python-imaging-library

According to the documentation, (at effbot.org): "You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the seek, tell, and write methods, and be opened in binary mode." This means you can pass a StringIO object....

PIL assistance Python

python,tkinter,syntax-error,python-imaging-library

You should really avoid from PIL Tkinter import * for obvious reasons but if you must then you can use from PIL import IMAGE as img to differentiate from the Tkinter Image

How to paste an image onto a larger image using Pillow?

python,python-imaging-library,pillow

The problem is in the first pasting - according to the PIL documentation (http://effbot.org/imagingbook/image.htm), if no "box" argument is passed, images' sizes must match. EDIT: I actually misunderstood the documentation, you are right, it's not there. But from what I tried here, it seems like passing no second argument, sizes...

How to resize image if max_width exceeds x with PIL?

python,django,python-imaging-library

It's certainly not pretty. I realize I have a lot of repeated code, but this is the only way I could figure out how to make it work. class ResizedImageFieldFile(ImageField.attr_class): def save(self, name, content, save=True): new_content = StringIO() content.file.seek(0) thumb = Image.open(content.file) if thumb.size[0] > 900: thumb.thumbnail(( self.field.max_width, self.field.max_height ),...

PIL simple gradient and TypeError: an integer is required

python,python-imaging-library

You are creating an Image with mode 'L' (single 8-bit pixel value), hence the value you put needs to be an int < 255. You are putting a tuple which requires the 'RGB' mode. I would think changing your code to img.putpixl((x,y), val) solves the issue.

Create circular image PIL Tkinter

python,user-interface,tkinter,python-imaging-library

Adapting from this answer (you need ImageOps and ImageDraw imported from PIL), you can create a circular mask for your zoomed image using: def create_mask(self): self.mask = Image.new('L', (200,200), 0) draw = ImageDraw.Draw(self.mask) draw.ellipse((0, 0) + self.mask.size, fill=255) Then, you have to apply the mask in your crop function: output...

Unable to delete file - File being used by another process

python,python-imaging-library,pillow

It may be related to this line: im = tmp = PIL.Image.open(outputfile) which does not actually open two copies of the image. Instead, you might want something like: im = PIL.Image.open(outputfile) tmp = im.copy() ...

Photologue UnsupportedOperation('fileno',)

python,django,python-imaging-library,pillow

I have fixed this issue by hard deleting the PIL lib from my system packages as even if I run my project in virtualenv it was still picking up PIL installed in the system packages. You should cautious when doing this as some other programs or project on your system...

Find which libjpeg is being used by PIL / PILLOW

python,python-imaging-library,libjpeg,pillow

First, locate the PIL egg that your Python installation is using: >>> import PIL >>> PIL.__path__ ['/usr/local/python/2.7.3/lib/python2.7/site-packages/PIL'] Then locate _imaging.so in that directory and use ldd (Linux) or otool -L (OS X) to find out what version of libjpeg it has been linked against: Linux $ ldd /usr/local/python/2.7.3/lib/python2.7/site-packages/PIL/_imaging.so linux-gate.so.1 =>...

Python PIL import Mac compatiblity

python,image,osx,python-imaging-library

Basically you can use any of the methods mentioned here. On my linux installation, PIL already uses one of those - there's a directory called PILcompat which has files like Image.py, and a file called PILcompat.pth which is used to tell python to add this directory to its module search...

Crop image with settable center and scale in Python PIL

python,image,zoom,python-imaging-library,crop

It is just a matter of getting the center and the sizes right. Determine the center of the spot where you want to crop Determine the new size using the scale factor Determine the bounding box of the cropped image The following script should do the trick. import os.path from...

Pillow: Can't draw text with right color in CMYK image

python,python-imaging-library,pillow

Mark Ransom wasn't far from the answer. fill=0(without quotes) is the way to get blank with CMYK image....

How can I use introspection to get Python to tell me more about PIL ImagingCore objects?

python,python-imaging-library,introspection

PIL's core functionality is implemented in module _imaging, written, as you guessed, in the C language -- see _imaging.c (3281 lines...:-) in the top level source directory, Imaging-1.1.7. That code doesn't pay any attention to introspection -- rather, it's 100% focused on performance. I believe it doesn't even bother to...

ImportError: DLL load failed: %1 is not a valid Win32 application for _imaging module

python,python-2.7,dll,python-imaging-library

The problem was solved by installing a 64 bit PILLOW module Pillow‑2.8.2‑cp34‑none‑win_amd64.whl from here