python学习-->opencv图像基本操作学习之灰度图转换

好久没更新,趁今天要做核酸回不了宿舍,把今天的学习的opencv知识先记录一下!

运行环境是:pycharm

话不多说,献上代码再说:

import cv2  # opencv读取的格式是BGR
import matplotlib.pyplot as plt
import numpy as np
# 读取图片;括号里面填写好路径就行!!
img = cv2.imread("./123.jpg")

print(img)
# 图像显示在窗口上面
# cv2.imshow("image", img)
# # 参数代表关闭图片后程序关闭的时间,数字越大时间越久
# cv2.waitKey(0)
# # 窗口关闭
# cv2.destroyAllWindows()
# shape方法:shape返回的是图像的行数,列数,色彩通道数
print(img.shape)
# (1440, 1080, 3)


# 改为灰色,图片转换为灰度图
img = cv2.imread("./123.jpg", cv2.IMREAD_GRAYSCALE)
print("*" * 100)
print(img)
print(img.shape)
# (1440, 1080)
cv2.imshow("image", img)
# 参数代表等待时间
cv2.waitKey(0)
# 窗口关闭
cv2.destroyAllWindows()


# 保存改变
cv2.imwrite("123.jpg", img)


# 查看图片类型
sd = type(img)
print(sd)
# 查看图片的总像素
img.size
print(img.size)
# 查看存储类型
img.dtype
print(img.dtype)

首先我们先读取我们的图片进来!

# 读取图片;括号里面填写好路径就行!!我这里当先目录下我导入的图片
img = cv2.imread("./123.jpg")

跟着我们先尝试一下在打开我们的图片看看!

下面是实现的代码!

# 图像显示在窗口上面
 cv2.imshow("image", img)
 # 参数代表关闭图片后程序关闭的时间,数字越大时间越久
 cv2.waitKey(0)
# 窗口关闭
 cv2.destroyAllWindows()

运行之后我的图片是这样的

我们可以看看图片具体的像素数据是怎么样的!

img = cv2.imread("./123.jpg")

print(img)

输出的结果是:

[[[129 129 129]
  [129 129 129]
  [129 129 129]
  ...
  [ 76  76  76]
  [ 77  77  77]
  [ 78  78  78]]

 [[129 129 129]
  [129 129 129]
  [129 129 129]
  ...
  [ 75  75  75]
  [ 76  76  76]
  [ 77  77  77]]

 [[129 129 129]
  [129 129 129]
  [129 129 129]
  ...
  [ 74  74  74]
  [ 75  75  75]
  [ 75  75  75]]

 ...

 [[160 160 160]
  [160 160 160]
  [161 161 161]
  ...
  [ 59  59  59]
  [ 60  60  60]
  [ 60  60  60]]

 [[160 160 160]
  [160 160 160]
  [160 160 160]
  ...
  [ 60  60  60]
  [ 60  60  60]
  [ 60  60  60]]

 [[159 159 159]
  [160 160 160]
  [160 160 160]
  ...
  [ 60  60  60]
  [ 60  60  60]
  [ 61  61  61]]]
有亿点点多!哈哈!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

这样完成了第一步!

这里我们顺便介绍一下shape的用法!

# shape方法:shape返回的是图像的行数,列数,色彩通道数
print(img.shape)
# (1440, 1080, 3)

第二步我们想这个彩色图片该改为灰度图片,因为在处理图片的时候有时候需要将图片改变为灰度图

# 改为灰色,图片转换为灰度图
img = cv2.imread("./123.jpg", cv2.IMREAD_GRAYSCALE)

完成这一步其实差不多了,然后呢,和刚刚开始一样

cv2.imshow("image", img)
 # 参数代表关闭图片后程序关闭的时间,数字越大时间越久
cv2.waitKey(0)
# 窗口关闭
cv2.destroyAllWindows()

还要补充一下

如果我们将123.jpg这一张图片改为灰度图之后;然后执行保存的话,那我们原先彩色的图片就会改为灰度图了。 变成下面的样子!

# 保存函数
cv2.imwrite("123.jpg", img)

最后我们顺便普及一下几个方法的作用:

# 查看图片类型
sd = type(img)
print(sd)
# 查看图片的总像素
img.size
print(img.size)
# 查看存储类型
img.dtype
print(img.dtype)

今天具体就分享这么多了,如果有上面有什么写错或者想和我交流,可以私信我哦!!!!

猜你喜欢

转载自blog.csdn.net/hhR888888/article/details/127659463
今日推荐