偏移图像框内的平铺形状

问题描述 投票:0回答:1

我有一幅图像,其中仅包含平铺的形状,其他所有地方均为黑色。但是,此平铺模式可以在图像中的任何位置(尤其是在图像边界上)移动/偏移。知道此形状可以在偏移了图像并保持黑色边框后适合图像内,我如何计算需要偏移的x和y坐标中有多少像素才能以最佳方式发生偏移?

输入图像enter image description here

偏移量/ shiftimg后所需的输出enter image description here

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

python image numpy opencv offset
1个回答
0
投票

因此,这是我在评论中使用Python / OpenCV / Numpy进行操作的详细信息。这是您想要的吗?

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

输入:

enter image description here

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)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.