在图像帧内偏移平铺形状

2024-05-29 03:04:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

输入图像 enter image description here

偏移/移位后的期望输出 enter image description here

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


Tags: 方法图像地方方式组件像素标签边框
1条回答
网友
1楼 · 发布于 2024-05-29 03:04:36

下面是我在评论中针对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

相关问题 更多 >

    热门问题