import cv2# Read image img = cv2.imread("imori.jpg") b = img[:,:,0].copy() g = img[:,:,1].copy() r = img[:,:,2].copy()# RGB > BGR img[:,:,0]= r img[:,:,1]= g img[:,:,2]= b# Save result cv2.imwrite("out.jpg", img) cv2.imshow("result", img) cv2.waitKey(0) cv2.destroyAllWindows()
这是原图
好了,执行看一下效果。
接下来看一个稍微复杂的例子。
Canny边缘强度检测
import cv2 import numpy as np import matplotlib.pyplot as plt# Read image img &#61; cv2.imread("imori.jpg").astype(np.float32) H, W, C &#61; img.shape# Gray gray &#61;0.2126* img[...,2]&#43;0.7152* img[...,1]&#43;0.0722* img[...,0]# Gaussian Filter K_size &#61;5 sigma &#61;1.4## Zero padding pad &#61; K_size //2 gau &#61; np.zeros((H &#43; pad*2, W &#43; pad*2), dtype&#61;np.float32) #gau[pad:pad&#43;H, pad:pad&#43;W] &#61; gray.copy().astype(np.float32) gau &#61; np.pad(gray,(pad, pad),&#39;edge&#39;) tmp &#61; gau.copy()## Kernel K &#61; np.zeros((K_size, K_size), dtype&#61;np.float32) for x inrange(-pad,-pad&#43;K_size):for y inrange(-pad,-pad&#43;K_size):K[y&#43;pad, x&#43;pad]&#61; np.exp(-(x**2&#43; y**2)/(2*(sigma**2))) K /&#61;(sigma * np.sqrt(2* np.pi)) K /&#61; K.sum()for y inrange(H):for x inrange(W):gau[pad&#43;y, pad&#43;x]&#61; np.sum(K * tmp[y:y&#43;K_size, x:x&#43;K_size])## Sobel vertical KSV &#61; np.array(((-1.,-2.,-1.),(0.,0.,0.),(1.,2.,1.)), dtype&#61;np.float32) ## Sobel horizontal KSH &#61; np.array(((-1.,0.,1.),(-2.,0.,2.),(-1.,0.,1.)), dtype&#61;np.float32)gau &#61; gau[pad-1:H&#43;pad&#43;1, pad-1:W&#43;pad&#43;1] fy &#61; np.zeros_like(gau, dtype&#61;np.float32) fx &#61; np.zeros_like(gau, dtype&#61;np.float32) K_size &#61;3 pad &#61; K_size //2for y inrange(H):for x inrange(W):fy[pad&#43;y, pad&#43;x]&#61; np.sum(KSV * gau[y:y&#43;K_size, x:x&#43;K_size])fx[pad&#43;y, pad&#43;x]&#61; np.sum(KSH * gau[y:y&#43;K_size, x:x&#43;K_size])fx &#61; fx[pad:pad&#43;H, pad:pad&#43;W] fy &#61; fy[pad:pad&#43;H, pad:pad&#43;W]# Non-maximum suppression edge &#61; np.sqrt(np.power(fx,2)&#43; np.power(fy,2)) fx[fx &#61;&#61;0]&#61;1e-5 tan &#61; np.arctan(fy / fx) ## Angle quantization angle &#61; np.zeros_like(tan, dtype&#61;np.uint8) angle[np.where((tan >-0.4142)&(tan <&#61;0.4142))]&#61;0 angle[np.where((tan >0.4142)&(tan <2.4142))]&#61;45 angle[np.where((tan >&#61;2.4142)|(tan <&#61;-2.4142))]&#61;95 angle[np.where((tan >-2.4142)&(tan <&#61;-0.4142))]&#61;135out &#61; angle.astype(np.uint8)# Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()