python - 偏移图像框架内的平铺形状
问题描述
我有一个图像,其中只包含一个平铺的形状,其他地方都是黑色的。然而,这种平铺图案可以在图像中的任何地方移动/偏移,特别是在图像边界上。知道这个形状可以在偏移它并留下黑色边框后适合图像,我如何计算需要偏移多少像素在 x 和 y 坐标中才能以优化的方式发生?
我的想法是在图像中获取连接的组件,检查边界上的标签,计算边界上每个轴形状之间的最长距离,并用这些值在轴上偏移。它可以工作,但我觉得应该有更聪明的方法。
解决方案
因此,这里是我在评论中使用 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)
推荐阅读
- python - 更正数据框中的错误值
- python - Plotly:在 hoverlabel 中以指定格式显示日期(customdata 将日期读取为字符串)
- c# - C# 表达式树:对象数组到 Expression.New() 参数
- excel - 用于检查 COG 是否在边界框中的 PowerQuery 公式
- javascript - 使用 Javascript/CSS 切换两个 HTML 元素的位置
- java - 你能帮我解决这个数组程序的最后一个 for 循环中出了什么问题吗
- php - 我如何在codeigniter中访问该函数之外的变量
- python - 在firestore的不同集合中查找具有相同ID的所有文档
- javascript - Javascript foreach 计算
- python - 从引入变量的 Lambda 查询 AWS Athena 时出现问题