图像处理轮廓
我正在写一个做基本图像处理的程序。
请注意,这些图像是灰度图,而不是RGB颜色图。此外,我对Python还比较陌生,所以如果能解释一下我做对了或错了什么,那将非常有帮助。
我想写一个轮廓算法,遵循以下规则:
原图中的所有亮色像素在轮廓图中必须是白色。
图像边缘上的所有暗色像素在轮廓图中必须是黑色。
如果一个像素不在图像的边缘,并且周围8个像素都是暗色的,那么这个像素就属于形状的内部,在轮廓图中必须是白色。
所有其他的暗色像素在轮廓图中必须是黑色。
到目前为止,我有这个:
def outlines(image):
"""
Finds the outlines of shapes in an image. The parameter must be
a two-dimensional list of pixels. The return value is another
two-dimensional list of pixels which describes an image showing
outlines of the shapes in the original image. Each pixel in the
return value will be either black (0) or white (255).
"""
height=len(image)
width=len(image[0])
new_image=[]
for r in range(height):
new_row=[]
index=0
for c in range(width):
if image[r][c]>128:
new_row.append(255)
if image[r][c]<=128:
new_row.append(0])
new_image.append(new_row)
有人能告诉我怎么把这个算法实现到我的轮廓函数里吗?
提前谢谢你们。
补充:这是我大学计算机科学课的作业,我不是在让别人帮我做作业,而是因为我几乎不知道下一步该怎么做。
补充2:如果有人能给我解释一个简单的边缘检测函数,类似于我需要创建的算法,我会非常感激。
1 个回答
1
除了检查你的像素是黑色还是透明之外,你还应该检查当像素是黑色时,周围的像素是否也都是黑色,这样才能把那个点变成白色。
看看这个函数,试着用它来实现这个目的:
def all_are_dark_around(image, r, c):
# range gives the bounds [-1, 0, 1]
# you could use the list directly. Probably better for this especific case
for i in range(-1,2):
for j in range(-1,2):
# if the pixel is clear return False.
# note that image[r+0][c+0] is always dark by definition
if image[r+i][c+j] <= 128:
return False
#the loop finished -> all pixels in the 3x3 square were dark
return True
一些建议:
- 要注意,当
r
或c
等于0
、height
或width
时,千万不要检查image[r][c]
。也就是说,当你检查的像素在边缘时,因为在这种情况下至少有一边是没有相邻像素的,这样会导致索引错误。 - 不要指望这段代码能直接工作,也不要期望它在效率或风格上是最好的。这只是给你的一点提示。你应该自己动手去做。所以看看这段代码,花点时间(最好花的时间和我写这个函数的时间一样长或更长),理解它是怎么工作的,并根据你的代码进行调整,修复你在过程中遇到的任何异常和边界情况。