ITPub博客

首页 > IT职业 > IT职场 > python物体标识如何实现

python物体标识如何实现

IT职场 作者:jinxiaoliang 时间:2021-09-11 09:47:13 0 删除 编辑

1、读取彩色图像进行灰度化和二值化。

def get_binary_img(img):
    # gray img to bin image
    bin_img = np.zeros(shape=(img.shape), dtype=np.uint8)
    h = img.shape[0]
    w = img.shape[1]
    for i in range(h):
        for j in range(w):
            bin_img[i][j] = 255 if img[i][j] < 255 else 0
    return bin_img
# 调用
file_name = "./test.bmp"
img = cv2.imread(file_name)
# 灰度化
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
bin_img = get_binary_img(gray_img)

2、目标标志,每个物体的像素值是该物体的标志,为计算面积打下基础。

# 标记目标
def label_region(bin_img,width,height):
    visited = np.zeros(shape=bin_img.shape,dtype=np.uint8)
    label_img = np.zeros(shape=bin_img.shape, dtype=np.uint8)
    label = 0
    for i in range(height):
        for j in range(width):
            if bin_img[i][j] == 255 and visited[i][j]==0 : //找到种子点
                # visit
                visited[i][j] = 1
                label += 1
                label_img[i][j] = label
                # label
                label_from_seed(bin_img, visited, i, j, label, label_img)
    return label_img
# 区域增长法进行标记
def label_from_seed(bin_img,visited,i,j,label,out_img):
    directs = [(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0)]
    seeds = [(i,j)]
    height = bin_img.shape[0]
    width = bin_img.shape[1]
    while len(seeds):
        seed = seeds.pop(0)
        i = seed[0]
        j = seed[1]
        if visited[i][j] == 0:
            visited[i][j] = 1
            out_img[i][j] = label
 
        # 以(i,j)为起点进行标记
        for direct in directs:
            cur_i = i + direct[0]
            cur_j = j + direct[1]
             # 非法
            if cur_i < 0 or cur_j < 0 or cur_i >= height or cur_j >= width:
                continue
             # 没有访问过
            if visited[cur_i][cur_j] == 0 and bin_img[cur_i][cur_j] == 255:
                visited[cur_i][cur_j] = 1
                out_img[cur_i][cur_j] = label
                seeds.append((cur_i,cur_j))

3、通过遍历标记的图像,统计每个编号中出现的像素数,可以得到不同区域的面积大小。

def get_region_area(label_img,label):
    count = { key: 0  for key in range(label + 1)}
    start_pt = {key:(0,0) for key in range(label + 1)}
    height = label_img.shape[0]
    width  = label_img.shape[1]
    for i in range(height):
        for j in range(width):
            key = label_img[i][j]
            count[key] += 1
            if count[key] == 1:
                start_pt[key] = (j,i)
    return count,start_pt

以上就是python物体标识的实现,希望对大家有所帮助。更多Python学习指路:python基础教程

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3996/viewspace-2828367/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-10-17

  • 博文量
    73
  • 访问量
    534