用PIL改进python中的行检测

2024-09-29 23:20:02 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我正在尝试用python检测图像中的白色条纹。这是我已经得到的代码:

def getPoints(self, image):
        threshold = 50
        whiteMin = 100 #Minimal average of the brightness in a lane
        minWidth = 1   #Min and Max width of a lane
        maxWidth = 8

        Points = []

        loadedImage = image.convert('L').load()

        for y in xrange(239, 479, 5):
            previousBrightness = loadedImage[127,y]

            lastDown = -1
            brightness = 0            

            for x in xrange(128, 511, 1):               
                currentBrightness = loadedImage[x,y]             
                difference = currentBrightness - previousBrightness               

                if difference > threshold: #if the current pixel is brighter than the previous and the difference is bigger than the threshold, set a flag
                    lastDown = x
                    brightness = currentBrightness                    
                elif -difference > threshold:                 
                    #check if the stripe has the correct width and the average brightness is high enough
                    if lastDown != -1 and x - lastDown < maxWidth and minWidth < x - lastDown and brightness / (x - lastDown) > whiteMin: 
                        Points.append(((x - lastDown) / 2 + lastDown,y))
                    lastDown = -1
                    brightness = 0
                elif lastDown != -1:
                    brightness += currentBrightness 

                previousBrightness = currentBrightness

        return Points

图像是一个PIL图像对象。你知道吗

我尝试过几种方法,比如使用getdata()-命令,使用getpixel()获取像素,首先裁剪图像或使用numpy数组,创建副本,滚动副本并从第一个数组中减去它。没有一个主题比我现在的版本快。你知道吗

我知道你可以使用PyPy来加速python代码,但是我想问的是,如果没有PyPy,我是否可以编写一个更快的版本。你知道吗

也许你们中有人有个好主意或者找到一个瓶子?你知道吗


Tags: andthe代码in图像thresholdifis

热门问题