偏移图像框架内的平铺形状

Offsetting a tiled shape inside the image frame

我有一个图像,其中只包含一个平铺形状,其他地方都是黑色的。但是,此平铺图案可以 shifted/offset 在图像中的任何位置,尤其是在图像边界上方。知道这个形状在偏移它并使边框保持黑色后可以适合图像内部,我如何计算 x 和 y 坐标中需要多少像素才能以优化的方式进行偏移?

输入图片

offset/shiftimg 后的期望输出

我的想法是获取图像中的连接组件,检查边界上有哪些标签,计算边界上每个轴形状之间的最长距离,并使用这些值在轴中进行偏移。它可以工作,但我觉得应该有更聪明的方法。

下面是我在评论中使用 Python/OpenCV/Numpy 所做的详细信息。这是你想要的吗?

  • 读取输入
  • 转换为灰色
  • 二进制的阈值
  • 计算每列中白色像素的个数并存入数组
  • 找到数组中的第一个和最后一个黑色(零计数)元素
  • 获取中心 x 值
  • 将图像裁剪成中心 x 的左右两部分
  • 将它们以相反的顺序水平堆叠在一起
  • 保存结果

输入:

import cv2
import numpy as np

# read image
img = cv2.imread('black_white.jpg')
hh, ww = img.shape[:2]

# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold
thresh = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)[1]

# count number of white pixels in columns as new array
count = np.count_nonzero(thresh, axis=0)

# get first and last x coordinate where black (count==0)
first_black = np.where(count==0)[0][0]
last_black = np.where(count==0)[0][-1]

# compute x center
black_center = (first_black + last_black) // 2
print(black_center)

# crop into two parts
left = img[0:hh, 0:black_center]
right = img[0:hh, black_center:ww]

# combine them horizontally after swapping
result = np.hstack([right, left])

# write result to disk
cv2.imwrite("black_white_rolled.jpg", result)

# display it
cv2.imshow("RESULT", result)
cv2.waitKey(0)