python物体标识怎么实现
这篇文章主要为大家展示了“python物体标识怎么实现”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“python物体标识怎么实现”这篇文章吧。
文县ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:028-86922220(备注:SSL证书合作)期待与您的合作!
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物体标识怎么实现
URL链接:http://scyanting.com/article/gsgidc.html