文章目录
1、访问图像中的所有像素
一个图像的像素数据=长×宽×通道,要获取相关信息,可以使用以下代码:
def access_pixels(image): # 访问图片的所有像素
print(image.shape) # 显示图像的长、宽、通道
height = image.shape[0]
width = image.shape[1]
channels = image.shape[2]
print("width: %s, height: %s, channels: %s" % (width, height, channels))
当我们要获取图像中的每一个像素,并对这些像素进行操作时,可以使用以下代码:
for row in range(height):
for col in range(width):
for c in range(channels):
pv = image[row, col, c]
image[row, col, c] = 255 - pv
cv.imshow("pixels_demo", image)
一张图像就是一个矩阵,因此我们可以通过for循环来读取,读取后,我们就可以进行我们想要的操作,最终结果为:
原图像为:
经过操作后改变的图像为:
从最右边的两把玄翦的对比可以看出,像素操作成功。
注:上述方法是手动对图像进行取反操作,而opencv中有相应的API可以完成该操作
dst = cv.bitwise_not(image)
经过上述代码后,显示出的图像为:
由图可得,bitwiae_not也能实现改功能。
在学习中,要不仅知其然,还要知其所以然
2、创建一张图像
一张图像包括长、宽、通道、像素、数据类型,因此创建一张三通道图片时,可以使用以下代码:
img = np.zeros([400, 400, 3], np.uint8)
该图像长400,宽400,通道数为3,数据类型为整形无符号,每个像素值为0,最终呈现的是一张全黑的图像。
若我们要对图像的第一个通道b进行操作时,可以使用以下代码:
img[: , : , 0] = np.ones([400, 400]) * 255
该段代码是对图像的第一个通道进行操作,np.ones是图像的每个像素值全部赋值为1,因此经过该操作后,呈现的是一张蓝色的图像。
注:图像的通道是指bgr,b是blue,g是green,r是red
当我们要创建一张单通道的图像时,
img = np.zeros([400, 400, 1], np.uint8)
img[: , : , 0] = np.ones([400, 400]) * 127
此时显示出的是一张灰色的图像,
同时上述的代码还可以更加精简,初始化一张灰色图像时,可以写为:
img = np.ones([400, 400, 1], np.uint8)
img = img * 127
完整的代码如下:
import cv2 as cv # 导入opencv模块
import numpy as np # 导入数学函数库
def access_pixels(image): # 访问图片的所有像素
print(image.shape) # 显示图像的长、宽、通道
height = image.shape[0]
width = image.shape[1]
channels = image.shape[2]
print("width: %s, height: %s, channels: %s" % (width, height, channels))
# 循环获取每一个像素点,进行改变
for row in range(height):
for col in range(width):
for c in range(channels):
pv = image[row, col, c]
image[row, col, c] = 255 - pv
cv.imshow("pixels_demo", image)
def inverse(image):
dst = cv.bitwise_not(image)
cv.imshow("inverse_image", dst)
def create_image():
# 三通道
"""
img = np.zeros([400, 400, 3], np.uint8)
img[: , : , 0] = np.ones([400, 400]) * 255 # img[:,:,0]是一种切片方式,冒号表示该维度从头到尾全部切片取出
# 所以img[:,:,0]表示切片取出所有行,所有列的第三个通道(索引为0)
cv.imshow("new_image", img)
"""
# 单通道
img = np.zeros([400, 400, 1], np.uint8)
img[:, :, 0] = np.ones([400, 400]) * 127
# img = np.ones([400, 400, 1], np.uint8)
# img = img * 127
cv.imshow("new_image", img)
ml = np.ones([3, 3], np.float32)
ml.fill(127.388)
print(ml)
print("------------hello python!------------")
src = cv.imread("D:/opencv3/image/eight J.jpg")
cv.namedWindow("input_image", cv.WINDOW_AUTOSIZE)
cv.imshow("input_image", src)
t1 = cv.getTickCount()
# access_pixels(src)
# create_image()
inverse(src)
t2 = cv.getTickCount()
time = (t2 - t1) / cv.getTickFrequency()
print("time: %s ms" % (time * 1000))
cv.waitKey(0)
cv.destroyAllWindows() # 释放所有窗口