Python 交叉图形计算
我正在努力寻找一种方法来计算PNG图片中一个或多个图形(如不同颜色的正方形/矩形)被其他正方形/矩形截取的次数。目标是编写一个函数,将PNG图片加载为包含元组的矩阵,其中每个元组表示RGB颜色模式下的颜色像素: 例如,黑色=(0,0,0)、白色=(255255)、红色=(255,0,0)等 确定一个地物与其他地物重叠的次数,并将信息保存在字典中,其中每个键表示地物颜色,每个值表示对同一地物的截取 如上图所示,所有正方形都有不同的颜色。我试图用下面的函数来解决这个问题Python 交叉图形计算,python,python-3.x,Python,Python 3.x,我正在努力寻找一种方法来计算PNG图片中一个或多个图形(如不同颜色的正方形/矩形)被其他正方形/矩形截取的次数。目标是编写一个函数,将PNG图片加载为包含元组的矩阵,其中每个元组表示RGB颜色模式下的颜色像素: 例如,黑色=(0,0,0)、白色=(255255)、红色=(255,0,0)等 确定一个地物与其他地物重叠的次数,并将信息保存在字典中,其中每个键表示地物颜色,每个值表示对同一地物的截取 如上图所示,所有正方形都有不同的颜色。我试图用下面的函数来解决这个问题 import images
import images
def intersections_reckoning(image_filename):
white = (255,255,255)
overlapping = {}
img = images.load(image_filename)
for i in img:
for j in range(len(i)):
count = 0
if i[j] == white:
continue
elif i[j] != i[j-1]:
count +=1
overlapping[i[j-1]] = count
return overlapping
这给了我以下错误的输出:
{(255, 255, 255): 1,
(255, 0, 0): 1,
(0, 0, 255): 1,
(0, 255, 0): 1,
(255, 255, 0): 1}
而不是
{(255, 0, 0): 4, --> red square is overlapped 4 times
(0, 0, 255): 0, --> blue square is not overlapped by any other figures. It intercepts others though
(0, 255, 0): 2, --> green square is overlapped twice
(255, 255, 0): 2} --> yellow square is overlapped twice
我该如何解决这个问题?。任何帮助都将不胜感激
谢谢以下是我的做法 首先,我们解析图像并查找彩色片段。我们将它们的x或y坐标添加到字典中,这取决于这些线段是垂直的还是水平的。这就给了我们,对于每个彩色矩形,四个坐标的dict
x1,y1,x2,y2
,它们代表该矩形的角。从那里我想你可以很容易地做一些数学计算,如果矩形彼此相交
我使用分段而不是相邻检查的原因是,如果与另一个矩形的交点是角点,否则此方法将失败
警告:如果与另一个矩形的交点是该矩形的整边,则我的方法在边缘情况下失败
import matplotlib.pyplot as plt
import numpy as np
# Create the image and rectangles.
N = 10
image = np.ones((N, N, 3), dtype=np.uint8)*255
blue = (0, 0, 255)
image[1, 2:6] = blue
image[1:6, 6] = blue
image[5, 2:6] = blue
image[2:6, 2] = blue
red = (255, 0, 0)
image[4, 5:9] = red
image[4:9, 5] = red
image[8, 5:9] = red
image[4:9, 9] = red
fig, ax = plt.subplots()
ax.set_xlim(0, N)
ax.set_ylim(0, N)
ax.imshow(image)
我不确定你的方法。我的方法是使用两个for循环在图像周围移动,沿着遇到的每个矩形的边界移动,然后退出循环,并且在存储中有一个列表,其中包含所有矩形角的坐标。完成后,使用数学确定与其他正方形的交点。如果你不关心效率,你也可以强制执行它,并检查XY1 XY2的
set(XY1)是否与set(XY2)相交一对矩形的坐标列表。你会使用嵌套循环吗?嗯,两个嵌套循环检查每个像素(img[i][j]
),然后循环遍历这些形状。@Guimoute您能再详细说明一下吗?
# Search for corners.
(X, Y, _) = image.shape
shapes = {}
for (name, color) in (("blue", blue), ("red", red)):
shape = shapes[name] = {}
# Searching for horizontal segments.
for x in range(X):
right_color = [True for b in image[x, :, :] == color if b.all()]
if len(right_color) >= 3:
if shape.get("x1") is None:
shape["x1"] = x
elif shape.get("x2") is None:
shape["x2"] = x
# Searching for vertical segments.
for y in range(Y):
right_color = [True for b in image[:, y, :] == color if b.all()]
if len(right_color) >= 3:
if shape.get("y1") is None:
shape["y1"] = y
elif shape.get("y2") is None:
shape["y2"] = y
print(shapes["blue"])
# >>> {'x1': 1, 'x2': 5, 'y1': 2, 'y2': 6}
print(shapes["red"])
# >>> {'x1': 4, 'x2': 8, 'y1': 5, 'y2': 9}
# Find the intersections.
NotImplemented