简体   繁体   中英

How to write lines and grid on image in Python?

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 <module>  
    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.

It seems you cannot convert it to a np.ndarray . Also, you should set the width parameter to a value different than 0 :

import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
from PIL import Image, ImageDraw


img = Image.open( 'test.tif' ).convert('L')

draw = ImageDraw.Draw(img)
draw.line((0,200, 1000,1000), fill=123., width=4)

plt.imshow(img, cmap=cm.Greys_r)
plt.savefig('test_changed.tif')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM