您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“python物體標識怎么實現”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“python物體標識怎么實現”這篇文章吧。
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物體標識怎么實現”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。