python - 如何修改适用于 RGB 图像的函数以使其适用于单色图像?
问题描述
下面的代码适用于 RGB 图像(对于形状:512x512x3)。我需要做的是让它适用于单通道单色图像。(形状:512x512)我应该修改哪些部分?
def get_triangle_colour(triangles, image, agg_func=np.median):
"""
Get's the colour of a triangle, based on applying agg_func to the pixels
under it
:param triangles: scipy.spatial.Delaunay
:param image: image as array
:param agg_func: function
:return: colour list
"""
# create a list of all pixel coordinates
ymax, xmax = image.shape[:2]
xx, yy = np.meshgrid(np.arange(xmax), np.arange(ymax))
pixel_coords = np.c_[xx.ravel(), yy.ravel()]
# for each pixel, identify which triangle it belongs to
triangles_for_coord = triangles.find_simplex(pixel_coords)
df = pd.DataFrame({
"triangle": triangles_for_coord,
"r": image.reshape(-1, 3)[:, 0],
"g": image.reshape(-1, 3)[:, 1],
"b": image.reshape(-1, 3)[:, 2]
})
#find the median color of the triangle
by_triangle = (
df
.groupby("triangle")
[["r", "g", "b"]]
.aggregate(agg_func)
.reindex(range(n_triangles), fill_value=0)
# some triangles might not have pixels in them
)
return by_triangle.values / 256
解决方案
作为一个非常快速、简单且内存效率极低且无需思考的第一次插入,您可以通过以下方式传递灰度图像的 RGB 版本(其中 R=G=B):
np.dstack((grey,grey,grey)) # or save a few keystrokes with np.dstack([grey]*3)
推荐阅读
- node.js - 获取引用的路径属性
- python - Python将模块移动到子目录(不破坏现有的导入结构)
- mysql - 通过 sql 计算用户看到的唯一项目
- java - 当您距离标记点不到 10 米时,如何开始一些方法?
- python - 使用 xlsxwriter 将一维 numpy 数组写入 excel
- java - 线程“主”org.apache.spark.sql.catalyst.parser.ParseException 中的异常
- javascript - 当用户 (A) 使用 Firebase 云功能和 Flutter 关注用户 (B) 时如何接收通知
- r - 使用 R DBI 包插入到
- ios - 在 swift 中使用 fscalendar 从 API 响应中获取事件的值
- spring-cloud-stream - 是否实现基于任务或流的方法