如何在Python中编写图像上的线条和网格?

时间:2013-08-04 15:22:53

标签: python image opencv matplotlib python-imaging-library

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()

我想在图像上放置一些网格线,但是会出现以下错误:

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'  

这段代码有什么问题?如何在图像上放置100x100网格?

2 个答案:

答案 0 :(得分:3)

这里的错误是你将PIL图像转换为numpy数组,但是你在numpy数组上使用了PIL ImageDraw库。

您可以在PIL或Numpy中绘制线条,无论您喜欢哪种,但是您需要使用Numpy处理Numpy对象和PIL来处理PIL对象。 Saullo在PIL中展示了如何做到这一点,你可以做到numpy:

img[:, 100:110] = 0

或网格为10像素宽,每100:

for i in range(100,1000,100):
    img[i:i+10,:] = 0
    img[:,i:i+10] = 0

作为旁注,您的导入有点疯狂,并且会破坏您的命名空间。对于你正在做的事情,你可以这样做:

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

例如,您只需要from numpy import *import numpy as np中的一个,但是一旦您已导入它,就会将其重新导入为其他名称。

答案 1 :(得分:0)

您似乎无法将其转换为np.ndarray。此外,您应将width参数设置为不同于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')