opencv 素描图
更多干货
代码
opencv 3.3.1 版本
调整 cv2.Canny(img,180,180) 中的数字 可以改变线条的多少
1.jpg 源图片
000.jpg 目标图片
个人感觉 第二种生成的素描图会好点
import cv2
import numpy as np
import random
img = cv2.imread('1.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
#canny 1 gray 2 高斯 3 canny
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgG = cv2.GaussianBlur(gray,(3,3),0)
dst = cv2.Canny(img,180,180) #图片卷积——》th
cv2.imwrite('000.jpg',dst) # 1 name 2 data
#颜色反转
imgfz = cv2.imread('000.jpg',1)
imgInfofz = imgfz.shape
dstfz = np.zeros((height,width,3),np.uint8)
for i in range(0,height):
for j in range(0,width):
(b,g,r) = imgfz[i,j]
dstfz[i,j] = (255-b,255-g,255-r)
#cv2.imshow('dstfz',dstfz)
cv2.imwrite('000.jpg',dstfz) # 1 name 2 data
cv2.waitKey(0)
第二种代码
import cv2
import numpy as np
import random
import math
img = cv2.imread('1.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
cv2.imshow('src',img)
# sobel 1 算子模版 2 图片卷积 3 阈值判决
# [1 2 1 [ 1 0 -1
# 0 0 0 2 0 -2
# -1 -2 -1 ] 1 0 -1 ]
# [1 2 3 4] [a b c d] a*1+b*2+c*3+d*4 = dst
# sqrt(a*a+b*b) = f>th
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
dst = np.zeros((height,width,1),np.uint8)
for i in range(0,height-2):
for j in range(0,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]+gray[i+1,j]*2+gray[i+2,j]-gray[i,j+2]-gray[i+1,j+2]*2-gray[i+2,j+2]
grad = math.sqrt(gx*gx+gy*gy)
if grad>100:
dst[i,j] = 0
else:
dst[i,j] = 255
cv2.imshow('dst',dst)
cv2.waitKey(0)