出现NoneType错误.convert

时间:2014-02-04 08:48:20

标签: python threshold

我想从网络摄像头捕获图像做一些程序,然后裁剪它。裁剪后,我做了一些图像处理,从这个过程中它将运行我的机器人。这里是完整的程序:

import cv2
from cv2 import *
import numpy as np
import pylab
import pymorph
import mahotas
from matplotlib import pyplot
from PIL import Image 

# initialize the camera
cam = VideoCapture(0)   # 0 -> index of camera
s, img = cam.read()

# frame captured without any errors
if s:    
    imwrite("img.jpg",img) #save image

#Crop Image
imageFile = "img.jpg"
im1 = Image.open(imageFile)

def imgCrop(im):

        box = (0, 199, 640, 200)
        region = im.crop(box)
        region.save('crop.jpg')

cImg = imgCrop(im1)

#thresholding
def greyImg(im):
    gray = im.convert('L')
    bw = gray.point(lambda x: 0 if x<128 else 255, '1')
    bw.save("bw.jpg")

tImg = greyImg(cImg )

#direction

def find_centroid(im, rez):
        width, height = im.size
        XX, YY, count = 0, 0, 0
        for x in xrange(0, width, rez):
            for y in xrange(0, height, rez):
                    if im.getpixel((x, y)) == 255:
                        XX += x
                        YY += y
                        count += 1
        return XX/count, YY/count

print find_centroid(tImg, 1)

def robo_direct():
    cen = find_centroid(im, 1)
    diff = cen[0] - 320
    if diff > 10:
        print 'right'
    if diff < -10:
        print 'left'
    else:
        print 'straight'

print robo_direct()

错误就是这样:

File "compile.py", line 32, in greyImg
gray = im.convert('L')
AttributeError: 'NoneType' object has no attribute 'convert'

2 个答案:

答案 0 :(得分:1)

这是因为im是一个None对象。

再次尝试使用以下代码:

print im is None

你会看到。我不知道阈值,但显然你是以错误的方式创建im对象。

答案 1 :(得分:0)

您的函数imgCrop(im1)没有返回语句,因此返回None。然后你的greyImg(im)函数也没有return语句,也会返回None

要修复将返回语句添加到第一个return region和第二个return bw的两个函数。

此外,您的robo_direct()函数应该返回并且不打印方向,以便在语句print robo_direct()中对它进行调用将打印方向。