个体识别的目的在于区分个体,区分个体则需要找到个体之间差异,因此使用边界阈值进行个体区分,这是最简单的实现方式。(后期将使用机器学习通过个体的色彩区分度、空间与时间的连续性对个体进行分析最终形成自然个体区分与识别,此处未对其实现)
此方法未采取多线程或多进程,故运行速度较慢,如想在此基础上改进运行速度可使用多线程或多进程。
测试图片和效果:
话不多说直接上代码:
from PIL import Image
import numpy
im = Image.open("BufferMemory/Test.jpg")
imData = numpy.array(im)
imShape = imData.shape
if len(imShape) > 2:
imHeigh, imWidth, imColorCnt = imShape
imGrayData = numpy.zeros((imHeigh, imWidth)).astype(numpy.uint8)
for y in range(imHeigh):
for x in range(imWidth):
imGrayData[y][x] = int(0.30 * imData[y][x][0] +
0.59 * imData[y][x][1] +
0.11 * imData[y][x][2])
else:
imHeigh, imWidth = imShape
imGrayData = imData
imGray = Image.fromarray(imGrayData)
imGray.save("tempGray/tempGray.bmp")
#形成个体
##基本个体
bodyData = numpy.zeros((imHeigh, imWidth)).astype(numpy.uint64)
##个体标志
bodyName = 0
##边缘阈值
defaultBoderNumber = 15
##产生基础个体
for y in range(imHeigh):
for x in range(imWidth):
#个体临时存储数组
tempbodylist = []
#开始识别基础个体
if int(bodyData[y][x]) == 0:
bodyName = bodyName + 1
bodyData[y][x] = bodyName
tempbodylist.append([x, y])
#个体判断
while len(tempbodylist) > 0:
#提取元素
tempX = tempbodylist[0][0]
tempY = tempbodylist[0][1]
#删除提取过的元素
tempbodylist = tempbodylist[1:]
#边缘分析
for cy in range(-1, 2):
for cx in range(-1, 2):
#防止越界
if tempY + cy < 0 or tempY + cy > imHeigh - 1 or tempX + cx < 0 or tempX + cx > imWidth - 1:
pass
else:
if abs(int(imGrayData[tempY][tempX]) - int(imGrayData[tempY + cy][tempX + cx])) < defaultBoderNumber:
#跳过已存在个体
if bodyData[tempY + cy][tempX + cx] > 0:
pass
else:
tempbodylist.append([tempX + cx, tempY + cy])
bodyData[tempY + cy][tempX + cx] = bodyName
else:
pass
print("Count Body : ",bodyName)
tempShowData = numpy.zeros((imHeigh, imWidth)).astype(numpy.uint8)
for i in range(bodyName):
#个体面积
area = 0
for y in range(imHeigh):
for x in range(imWidth):
if bodyData[y][x] == i+1:
area = area + 1
tempShowData[y][x] = 255
else:
tempShowData[y][x] = 0
if area > 20:
tempShow = Image.fromarray(tempShowData)
tempShow.save("tempBody/{}.bmp".format(i+1))