利用区域生长法绘画一个白色矩形框
首先簡單介紹一下數字圖像處理中的區域生長法
在應用區域生長法時,需要考慮三個問題
1、種子像素是哪些或者哪一個
選擇和確定一組能夠代表種子像素的一般原則為:
(1)接近聚類中心的像素可以作為種子像素
(2)紅外圖像目標檢測中最亮的像素可作為種子像素
(3)按照位置要求確定種子像素
(4)根據某種經驗確定種子像素
2、確定在生長過程中能將相鄰像素合并進來的相似性準則
確定相似性準則的準則主要有:
(1)考慮自己所要處理的問題所需,例如需要找到灰度性差不多的點,那就應該考慮待檢測的點與已合并區域中的所有像素點的平均值是否滿足某種相似性準則,通俗地講,也就是說灰度值大小滿不滿足你想并進來的條件。
(2)尺寸要求、形狀要求,圖像顏色等
3、確定終止生長過程的條件或規則
(1)一般的停止生長準則是生長過程進行到沒有滿足生長準則的像素為止
當然也可以加入你所處理的問題所需要的要求來確定,例如形狀要求、尺寸要求等
本文利用區域生長法繪畫一個白色矩形框,其實質相當于是給一個圖像,設定一個形狀限制條件,的像素點進行灰度值賦值。
用剛剛介紹的考慮三個問題來解釋一下:
種子像素:自己手動選取的圖像中的一個點
相似性準則:滿足圖像形狀即可
終止生長的條件:匯完白色矩形框即可
舉出這個例子初衷是讓讀者對于區域生長有一個較為初步的認識
下面是實現繪畫白色矩形框的程序,其中定義的區域生長的類方法的還有很大的可優化空間,就交給讀者去優化了。
import numpy as np import cv2class RegionGrow:"""區域生長成一條矩形框"""def __init__(self, x, y, width, length, img_height, img_width):"""區域生長的點以及圖像的高寬設置"""self.x = xself.y = y# 自定義的線寬self.width = width# 自定義的線長self.length = length# 生成一個黑色圖像self.img = np.zeros([img_height, img_width])self.img_height = img_heightself.img_width = img_widthdef grow_length(self):print(self.img.shape)self.label = 255length_source = 1# 矩形框長度初值for length in range(1, self.length):"""將矩形的左邊長和上邊長繪畫出來"""self.line_new_x = self.x + length_sourceself.line_new_y = self.y + length_sourceif self.line_new_x < self.img_height - 20 and self.line_new_y < self.img_width - 20:# 在x方向上進行區域生長self.img[self.line_new_x, self.y] = self.label# 在y方向上進行區域生長self.img[self.x, self.line_new_y] = self.labellength_source += 1print(f"{self.line_new_x}-{self.y},{self.x}-{self.line_new_y} ")length_source_1 = 1for length_1 in range(1, self.length):"""將舉行的下邊長以及右邊長進行繪畫出來"""self.line_new_y1 = self.y + length_source_1self.line_new_x1 = self.x + length_source_1if self.line_new_x1 < self.img_height - 20 and self.line_new_y1 < self.img_width - 20:# 在區域增長到一個新的起點之后,按照新的起點繼續,此為矩形的下邊長self.img[self.line_new_x, self.line_new_y1] = self.label# 在區域增長到一個新的起點之后,按照新的起點繼續,此為矩形的右邊長self.img[self.line_new_x1, self.line_new_y] = self.labellength_source_1 += 1print(f"{self.line_new_x}--{self.line_new_y1}, {self.line_new_x1}--{self.line_new_y}")def grow_width(self):"""將繪畫的矩形線寬度從1像素變為self.width大小的像素"""i = 1for length in range(self.x, self.line_new_x + 1):width = self.widthi = 1while width > 0:"""將矩形的左邊長和上邊長繪畫出來""""""將矩形的左邊長加寬"""self.img[length, self.y + i] = self.label"""將矩形的上邊長加寬"""self.img[self.x + i, length] = self.label"""將矩形的右邊長加寬"""self.img[length, self.line_new_y - i] = self.label"""將矩形的下邊長加寬"""self.img[self.line_new_x - i, length] = self.labeli += 1width -= 1img_region_grow = RegionGrow(20, 20, 50, 760, 800, 800) img_region_grow.grow_length() img_region_grow.grow_width() cv2.imshow('img_region_grow', img_region_grow.img) cv2.imwrite('C:\\Users\\yu\\Desktop\\picture_csdn\\img_region_a_line.png', img_region_grow.img) cv2.waitKey(0) cv2.destroyAllWindows()實現的效果圖如下:
程序中新建的一個黑色圖像?
?
區域生長完成后的圖像?
總結
以上是生活随笔為你收集整理的利用区域生长法绘画一个白色矩形框的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为此客画上一个句号
- 下一篇: Python tkinter多窗口的交互