首页 > 其他 > 详细

opencv对图片每个像素操作

时间:2020-02-07 09:16:21      阅读:71      评论:0      收藏:0      [点我收藏+]

1.遍历图像对其每个像素取反

import cv2 as cv
import numpy as np

img = cv.imread("d:/girl.jfif")
cv.imshow("img", img)

height = img.shape[0]
width = img.shape[1]
channels = img.shape[2]
t1 = cv.getTickCount()
for h in range(height):
    for w in range(width):
        for c in range(channels):
            img[h, w, c] = 255 - img[h, w, c]
t2 = cv.getTickCount()
t = (t2 - t1)/cv.getTickFrequency()*1000
print("%f ms"%t)
cv.imshow("img2", img)
cv.waitKey(0)

注意cv.getTickCount()的使用可以获得程序运行时间。

t = (t2 - t1)/cv.getTickFrequency()*1000

其中t的单位是毫秒

 顺便一提,可以使用cv.bitwise_not(image)来实现对图像取反,比上面的代码要快几千倍。事实上,还有bitwise_and, bitwise_or, bitwise_xor等位操作的函数

 

2.构造一张蓝色的图

‘‘‘
构造一张蓝色的图
‘‘‘
import cv2 as cv
import numpy as np

img = np.zeros(shape=[400, 400, 3], dtype=np.uint8)
img[:,:,0] = np.ones([400, 400])*255
cv.imshow("img", img)
cv.waitKey(0)

三通道,bgr,所以只需要对第三维的索引0赋值。

 

3.构造单通道灰度图

‘‘‘
构造一张灰色的图
‘‘‘
import cv2 as cv
import numpy as np

img = np.ones(shape=[400, 400, 1], dtype=np.uint8)
height = img.shape[0]
width = img.shape[1]
channels = img.shape[2]
for h in range(height):
    for w in range(width):
        for c in range(channels):
            img[h, w, c] = (h+w)%255
cv.imshow("img", img)
cv.waitKey(0)

结果很漂亮惹,懒得截图了

 

opencv对图片每个像素操作

原文:https://www.cnblogs.com/loubin/p/12271412.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!