首页 > 解决方案 > 偏移图像框架内的平铺形状

问题描述

我有一个图像,其中只包含一个平铺的形状,其他地方都是黑色的。然而,这种平铺图案可以在图像中的任何地方移动/偏移,特别是在图像边界上。知道这个形状可以在偏移它并留下黑色边框后适合图像,我如何计算需要偏移多少像素在 x 和 y 坐标中才能以优化的方式发生?

输入图像 在此处输入图像描述

偏移/shiftimg 后所需的输出 在此处输入图像描述

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

标签: pythonimagenumpyopencvoffset

解决方案


因此,这里是我在评论中使用 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)


在此处输入图像描述


推荐阅读