计算机视觉:图片的边缘检测映射和油画效果
Posted il_持之以恒_li
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计算机视觉:图片的边缘检测映射和油画效果相关的知识,希望对你有一定的参考价值。
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]
# b = b*1.5
# g = g*1.3
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
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) # p1 0~3
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)
以上是关于计算机视觉:图片的边缘检测映射和油画效果的主要内容,如果未能解决你的问题,请参考以下文章
Python 计算机视觉(补充版)—— 图像特效中的油画效果