python画函数图像网格,如何在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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值