我想在python3中编写一个代码,用于检测图像中的对象形状。
我想从给定图像中的对象中选择一个像素并找到邻居像素。
如果它们具有相同的RGB值,则意味着它们是对象的一部分。
当相邻像素以与原始像素的可调差异来改变RGB值时,算法应该停止搜索邻居。我认为除非背景和物体具有相同的颜色,否则这将起作用。
我找到了一种方法将相同颜色的像素放在一个矩形中,但这对我没有帮助。我想只保存对象的形状并将其放在不同的图像中。
例如,
如果我想从对象的中间开始算法,那就试试吧 说一个带有白色背景的黑色表,算法会找到 在任何方向上具有相同颜色的像素。
当邻居像素 RGB值将在一个方向上变化超过30个单位 算法将停止朝那个方向前进,并将开始进入 另一个方向,直到我有桌子的形状。
我在另一篇文章中找到了一个代码,帮助我使用PIL确定具有共享值的像素区域
谢谢!
from collections import defaultdict
from PIL import Image, ImageDraw
def connected_components(edges):
"""
Given a graph represented by edges (i.e. pairs of nodes), generate its
connected components as sets of nodes.
Time complexity is linear with respect to the number of edges.
"""
neighbors = defaultdict(set)
for a, b in edges:
neighbors[a].add(b)
neighbors[b].add(a)
seen = set()
def component(node, neighbors=neighbors, seen=seen, see=seen.add):
unseen = set([node])
next_unseen = unseen.pop
while unseen:
node = next_unseen()
see(node)
unseen |= neighbors[node] - seen
yield node
return (set(component(node)) for node in neighbors if node not in seen)
def matching_pixels(image, test):
"""
Generate all pixel coordinates where pixel satisfies test.
"""
width, height = image.size
pixels = image.load()
for x in xrange(width):
for y in xrange(height):
if test(pixels[x, y]):
yield x, y
def make_edges(coordinates):
"""
Generate all pairs of neighboring pixel coordinates.
"""
coordinates = set(coordinates)
for x, y in coordinates:
if (x - 1, y - 1) in coordinates:
yield (x, y), (x - 1, y - 1)
if (x, y - 1) in coordinates:
yield (x, y), (x, y - 1)
if (x + 1, y - 1) in coordinates:
yield (x, y), (x + 1, y - 1)
if (x - 1, y) in coordinates:
yield (x, y), (x - 1, y)
yield (x, y), (x, y)
def boundingbox(coordinates):
"""
Return the bounding box of all coordinates.
"""
xs, ys = zip(*coordinates)
return min(xs), min(ys), max(xs), max(ys)
def disjoint_areas(image, test):
"""
Return the bounding boxes of all non-consecutive areas
who's pixels satisfy test.
"""
for each in connected_components(make_edges(matching_pixels(image, test))):
yield boundingbox(each)
def is_black_enough(pixel):
r, g, b = pixel
return r < 10 and g < 10 and b < 10
if __name__ == '__main__':
image = Image.open('some_image.jpg')
draw = ImageDraw.Draw(image)
for rect in disjoint_areas(image, is_black_enough):
draw.rectangle(rect, outline=(255, 0, 0))
image.show()
答案 0 :(得分:0)
尝试使用Python的opencv。 使用opencv,您可以进行高级图像分析,并且有许多教程可以使用它。 http://www.pyimagesearch.com/2014/04/21/building-pokedex-python-finding-game-boy-screen-step-4-6/