opencv實現回形遍歷像素算法

本文實例為大傢分享瞭opencv實現回形遍歷像素算法的具體代碼,供大傢參考,具體內容如下

代碼實現

# -*- coding:utf-8 -*-
import cv2
import numpy as np
 
cv2.namedWindow('img', 0)
 
 
def traversePixelByCycloidLine(image):
 """
 從一副灰度圖像的中心開始向邊緣按回形線的方式遍歷所有像素,每個像素隻能訪問一次。
 我目前實現瞭基本的算法, 但存在以下問題:
 1) 隻支持方陣, 且行列為奇數
 2) 隻實現, 代碼沒整理
 """
 
 h, w = image.shape[:2]
 
 assert h == w and h % 2 == 1, '隻支持方陣, 且行列為奇數'
 
 center_x, center_y = [w // 2, h // 2]
 
 traverse_num = h * w
 
 cycloid_num = 0
 value = 1
 while True:
 
  for i in range(cycloid_num * 2 + 1):
   if value >= traverse_num:
    return image
   center_x = center_x + 1
   image[center_y, center_x] = 255
   value += 1
   cv2.imshow('img', image)
   cv2.waitKey(33)
 
  for i in range(cycloid_num * 2 + 1):
   if value >= traverse_num:
    return image
   center_y = center_y + 1
   image[center_y, center_x] = 255
   value += 1
   cv2.imshow('img', image)
   cv2.waitKey(33)
 
  for i in range(cycloid_num * 2 + 2):
   if value >= traverse_num:
    return image
   center_x = center_x - 1
   image[center_y, center_x] = 255
   value += 1
   cv2.imshow('img', image)
   cv2.waitKey(33)
 
  for i in range(cycloid_num * 2 + 2):
   if value >= traverse_num:
    return image
   center_y = center_y - 1
   image[center_y, center_x] = 255
   value += 1
   cv2.imshow('img', image)
   cv2.waitKey(33)
  cycloid_num += 1
 
 
image_wh = 11
 
while True:
 image = np.zeros((image_wh, image_wh, 3), dtype=np.uint8)
 traversePixelByCycloidLine(image)

效果展示

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: