python - 使用 numpy 将图像转换为灰度
问题描述
我有一个由三元组numpy.array
矩阵nxm(r,g,b)
表示的图像,我想使用我自己的函数将其转换为灰度。
我的尝试将矩阵nxmx3转换为单值矩阵nxm失败,这意味着从[r,g,b]
我得到[gray, gray, gray]
但我需要的数组开始gray
。
即初始颜色通道:[150 246 98]
。转换为灰色后:[134 134 134]
。我需要的 : 134
我怎样才能做到这一点?
我的代码:
def grayConversion(image):
height, width, channel = image.shape
for i in range(0, height):
for j in range(0, width):
blueComponent = image[i][j][0]
greenComponent = image[i][j][1]
redComponent = image[i][j][2]
grayValue = 0.07 * blueComponent + 0.72 * greenComponent + 0.21 * redComponent
image[i][j] = grayValue
cv2.imshow("GrayScale",image)
return image
解决方案
这是一个工作代码:
def grayConversion(image):
grayValue = 0.07 * image[:,:,2] + 0.72 * image[:,:,1] + 0.21 * image[:,:,0]
gray_img = grayValue.astype(np.uint8)
return gray_img
orig = cv2.imread(r'C:\Users\Jackson\Desktop\drum.png', 1)
g = grayConversion(orig)
cv2.imshow("Original", orig)
cv2.imshow("GrayScale", g)
cv2.waitKey(0)
cv2.destroyAllWindows()
推荐阅读
- sql - 我的查询需要超过 30 分钟,即使它会显示结果也不确定
- python - 快速 API 帖子无法识别我的参数
- java - 为什么继承类方法在 Java 中打印 0 和 null?
- php - 如何获取url路径
- javascript - 重构javascript代码反应redux问题
- oauth-2.0 - oauth 如何与主要平台配合使用,例如。脸书和谷歌?
- vue.js - 在 this.$axios.post 之后重定向到另一个页面有问题
- python - Python Cassandra 驱动程序未安装,或未安装在 Ubuntu 上的 PYTHONPATH 上
- android - 为 iOS 或 Android 自定义 Flutter 应用程序中的 Native Alert 对话框以实现 Face Id
- android - 复杂错误:使用自定义测试文件夹时 androidx.test.ext.junit.runners 不存在