I have this image
enter image description here
I need to find an empty area that can fit this shape
enter image description here
so that the end result is something like this
enter image description here

推荐答案

对于这个问题,这里有一个简单而幼稚的解决方案.它使用UnquoteQuote中提到的2D卷积.

import random
import numpy as np
import scipy.signal as sig
import matplotlib.pyplot as plt
import cv2

# load images
image = (cv2.imread('image.jpg').mean(axis=2) > 127).astype(np.float32)
shape = (cv2.imread('shape.jpg').mean(axis=2) > 127).astype(np.float32)

# perform 2D convolution
conv = sig.convolve2d(image, shape, mode='valid')
solutions = np.where(conv == 0)

# draw some solutions
plt.figure(figsize=(16, 4))
for i in range(4):
    r = random.randint(0, solutions[0].shape[0] - 1)
    x, y = solutions[0][r], solutions[1][r]

    solution_plot = np.zeros((*image.shape, 3))
    solution_plot[:, :, 0] = image
    solution_plot[x:x + shape.shape[0], y:y + shape.shape[1], 1] = shape

    plt.subplot(1, 4, i + 1)
    plt.imshow(solution_plot)

plt.show()

Example results: enter image description here

该算法可以找到所有可能的解决方案.如果你只需要一个,你可以优化它,使它得到一个随机的(x, y)点,并执行形状和裁剪图像区域[x:x+shape_width, y:y+shape_height]的点积,以判断是否有空间,直到你找到正确的点.

例如,可以这样做:

while True:
    x = random.randint(0, image.shape[0] - shape.shape[0])
    y = random.randint(0, image.shape[1] - shape.shape[1])

    if np.sum(shape*image[x:x + shape.shape[0], y:y + shape.shape[1]]) == 0:
        break

# x, y is the solution

与卷积相比,这种方法要快得多(但这取决于解的数量):

  • 卷积:6.65 s ± 21.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
  • 随机搜索:1.31 ms ± 31.2 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

Python相关问答推荐

Pandas 修改原始excel

Plotly Dash函数来切换图形参数-pPython

解析讨论论坛只给我第一个用户 comments ,但没有给我其他用户回复

如何在Python中使用ijson解析SON期间检索文件位置?

Polars:使用列值引用when / then表达中的其他列

多处理代码在while循环中不工作

Python上的Instagram API:缺少client_id参数"

在Pandas DataFrame操作中用链接替换'方法的更有效方法

Pandas - groupby字符串字段并按时间范围 Select

大小为M的第N位_计数(或人口计数)的公式

如何在solve()之后获得症状上的等式的值

有没有一种方法可以从python的pussompy比较结果中提取文本?

如何在Polars中从列表中的所有 struct 中 Select 字段?

迭代嵌套字典的值

如何使用scipy的curve_fit与约束,其中拟合的曲线总是在观测值之下?

删除marplotlib条形图上的底边

使用Python从URL下载Excel文件

用渐近模计算含符号的矩阵乘法

使用Python查找、替换和调整PDF中的图像'

* 动态地 * 修饰Python中的递归函数