题目描述
思路:
1.图像填充 填充后的图像,即为img1可以平移的所有情况
2.卷积
class Solution(object):
def largestOverlap(self, img1, img2):
"""
:type img1: List[List[int]]
:type img2: List[List[int]]
:rtype: int
"""
n=len(img1)
#填充图像,使得图像各种平移变换都涵盖到新的大图像中
def filling(img):
m=2*(n-1)+n
image=[[0]*m for _ in range(m)]
for i in range(n):
for j in range(n):
if img[i][j]==1:
new_i,new_j=i+n-1,j+n-1
image[new_i][new_j]=1
return image
image=filling(img1)
m=len(image)
#把img2作为卷积核,image作为待卷积图像,计算过程中出现的最大重合数
#卷积核中为1 得位置记录下来
one_position = []
for dx in range(n):
for dy in range(n):
if img2[dx][dy] == 1:
one_position.append([dx, dy])
res = 0
for start_i in range(m- n + 1):
for start_j in range(m- n + 1):
tmp = 0
for dx, dy in one_position:
tmp += image[start_i + dx][start_j + dy]
res = max(res, tmp)
if res==len(one_position):return res
return res
调包
from scipy.signal import correlate2d
class Solution:
def largestOverlap(self, A, B):
return correlate2d(A, B).max()
官网方法:link