1.图片的边缘检测
1.1 调用cv2 api方法
import cv2
img = cv2.imread(filename='../anqila21.jpg',flags=1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgG = cv2.GaussianBlur(gray,(3,3),0)
dst = cv2.Canny(imgG,50,50)
cv2.imshow('dst',dst)
cv2.waitKey(0)
1.2 算法实现
现在我们使用算法实现,并且把它的背景颜色改为白色,线条颜色改为黑色,为了让效果更加明了,换一张大一点的图片。
import cv2
import numpy as np
import math
img = cv2.imread(filename='../../anqila.jpg',flags=1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
dst = np.zeros((height,width,1),np.uint8)
'''
sobel
[ 1 2 1 [ 1 0 -1
0 0 0 2 0 -2
-1 -2 -1] 1 0 -1]
'''
for i in range(height-2):
for j in range(width-2):
gy = gray[i,j]*1+gray[i,j+1]*2+gray[i,j+2]*1-gray[i+2,j]*1-gray[i+2,j+1]*2-gray[i+2,j+2]*1
gx = gray[i,j]*1-gray[i,j+2]*1+gray[i+1,j]*2-gray[i+1,j+2]*2+gray[i+2,j]*1-gray[i+2,j+2]*1
grad = math.sqrt(gx**2+gy**2)
if grad >50:
dst[i,j] = 0
else:
dst[i,j] = 255
cv2.imshow('dst',dst)
cv2.waitKey(0)
2. 图片的映射
import cv2
import numpy as np
img = cv2.imread(filename='../anqila21.jpg',flags=1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
dst = np.zeros((height,width,3),np.uint8)
for i in range(height):
for j in range(width):
(b,g,r) = img[i,j]
b = b*1.5
g = g*1.3
if b>255:
b = 255
if g>255:
g = 255
dst[i,j]=(b,g,r)
cv2.imshow('dst',dst)
cv2.waitKey(0)
是不是觉得有点像电影里面的效果了呢?
3. 图片的油画效果
import cv2
import numpy as np
img = cv2.imread(filename='../anqila21.jpg',flags=1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
dst = np.zeros((height,width,3),np.uint8)
flag = 2
for i in range(flag,height-flag):
for j in range(flag,width-flag):
array1 = np.zeros(8,np.uint8)
for m in range(-1*flag,flag):
for n in range(-1*flag,flag):
p1 = int(gray[i+m,j+n]/32)
array1[p1]+=1
currentMax = array1[0]
l = 0
for k in range(1,8):
if currentMax<array1[k]:
currentMax = array1[k]
l = k
for m in range(-1 * flag, flag):
for n in range(-1 * flag, flag):
if (l * 32) <= gray[i + m, j + n] <= ((l + 1) * 32):
(b,g,r) = img[i+m,j+n]
dst[i,j] = (b,g,r)
cv2.imshow('dst',dst)
cv2.waitKey(0)
|