import numpy as np
from matplotlib import cm
from matplotlib import pyplot as plt
import Image
from scipy import ndimage
import Image, ImageDraw
import PIL
import cv
import cv2
from scipy.ndimage import measurements, morphology
from PIL import Image
from numpy import *
from scipy.ndimage import filters
import pylab
import mahotas
from mamba import*
import mambaDraw
from PIL import Image, ImageDraw
img = np.asarray(Image.open('test.tif').convert('L'))
img = 1 * (img < 127)
draw = ImageDraw.Draw(img)
draw.line((100,200, 150,300), fill=128)
plt.imshow(img, cmap=cm.Greys_r)
plt.show()
I want to put some grid lines on image, but get the following error:
Traceback (most recent call last):
File "C:\Documents and Settings\All Users.WINDOWS\Документыline 24, in
draw = ImageDraw.Draw(img)
File "C:\Python27\lib\site-packages\PIL\ImageDraw.py", line 296, in Draw
return ImageDraw(im, mode)
File "C:\Python27\lib\site-packages\PIL\ImageDraw.py", line 61, in __init__
im.load()
AttributeError: 'numpy.ndarray' object has no attribute 'load'
What is wrong with this code? How do I put a 100x100 grid on an image?
解决方案
Your error here is that you convert a PIL image to a numpy array, but then you use the PIL ImageDraw library on the numpy array.
You can draw the lines in either PIL or Numpy, whichever you prefer, but you need to use Numpy to work with Numpy objects and PIL to work with PIL objects. Saullo showed how to do it in PIL, in numpy you could do:
img[:, 100:110] = 0
or for a grid 10 pixels wide, every 100:
for i in range(100,1000,100):
img[i:i+10,:] = 0
img[:,i:i+10] = 0
As a side note, your imports are a bit crazy and are messing up your namespace. For what you're doing, you can just do:
import numpy as np
import Image, ImageDraw
# and for a reasonable import of other packages you've listed
from matplotlib import cm
from matplotlib import pyplot as plt
from scipy import ndimage
import cv2
import mahotas
import mambaDraw
For example, you only need one of from numpy import * or import numpy as np, but once you've already imported it, it complicates things to reimport it as some other name.