如何在Python中编写图像上的线条和网格? [英] How to write lines and grid on image in Python?

查看:3076
本文介绍了如何在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'  

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

What is wrong with this code? How do I put a 100x100 grid on an image?

推荐答案

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

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.

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

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

或网格10像素宽,每100:

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

例如,你只需要一个从numpy import * 导入numpy为np ,但是一旦你已经导入它,它就会像其他一些东西一样重新导入它名字。

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.

这篇关于如何在Python中编写图像上的线条和网格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆