图
我们读取图片每一个像素值, 我们需要一个好用又快速的 python 库来实现操作数组库 numpy. 通常会使用 numpy 来遍历图形的每一个像素点. 通过修改像素点来改变图像.
也会介绍一些我们在 opencv 来用到有关 opencv 的 numpy 常用操作.
- 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))
- access_pixels(img)
从输出上来看是一个 3 维矩阵, 一维 512 为图像宽度而第二个维度 512 为图像高度, 最后每个为 3 维像素值, 代表图形的 BRG, 注意 opencv 读取图片是 BRG 而不是 RGB 格式我们需要进行转换.
- (512, 512, 3)
- width: 512, height: 512, channels:3
在 ps 有反色处理, 今天我们通过遍历每一个像素然后 255 减去每一个像素值来对图片进行取反. 达到反色的效果.
- 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
- cv2.imshow('processed',image)
图片
- def create_image():
- img = np.zeros([400,400,3],np.uint8)
- cv2.imshow('img',img)
- img[:,:,1] = np.ones([400,400])* 255
出现一张绿色图片, 宽度和高度分别为 400
- import cv2
- import numpy as np
- # events = [i for i in dir(cv2) if 'EVENT' in i]
- # print(events)
- def click_event(event, x, y, flags, param):
- if event == cv2.EVENT_LBUTTONDOWN:
- cv2.circle(img,(x,y), 3, (0,255,0),-1)
- points.append((x,y))
- if len(points)>= 2:
- cv2.line(img,points[-1],points[-2], (255,0,0),5)
- cv2.imshow('image',img)
- # img = np.zeros((512,512,3),np.uint8)
- img = cv2.imread('lena.jpg')
- cv2.imshow('image',img)
- points = []
- cv2.setMouseCallback('image',click_event)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
结合之间学习的鼠标左键事件, 以及今天学习通过 numpy 来获取像素来实现在图片进行绘制线条的效果.
图
- import cv2
- import numpy as np
- # events = [i for i in dir(cv2) if 'EVENT' in i]
- # print(events)
- def click_event(event, x, y, flags, param):
- if event == cv2.EVENT_LBUTTONDOWN:
- blue = img[x,y,0]
- green = img[x,y,1]
- red = img[x,y,2]
- cv2.circle(img,(x,y),3,(0,0,255),-1)
- mColorImage = np.zeros((512,512,3),np.uint8)
- mColorImage[:] = [blue,green,red]
- cv2.imshow('color',mColorImage)
- # img = np.zeros((512,512,3),np.uint8)
- img = cv2.imread('lena.jpg')
- cv2.imshow('image',img)
- points = []
- cv2.setMouseCallback('image',click_event)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
来源: http://www.jianshu.com/p/c1942f86edc9