制作油画效果的步骤如下:
- 读取维度信息
- 读取灰度图片
- 求最大灰度段中各通道值
- 颜色封装
- 显示油画效果图
# 1 gray 2 7*7 or 10*10 3 灰度等级的划分 0~255
# 4 count 5 dst = result
import cv2
import numpy as np
import random
import math
# 1 读取维度信息
img = cv2.imread('face.jpg', 1)
cv2.imshow('src', img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
cv2.imshow('shape', imgInfo)
# 2 读取灰度图片
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 3 求最大灰度段中的各通道值,并封装
dst = np.zeros((height, width, 3), np.uint8)
for i in range(4, height - 4):
for j in range(4, width - 4):
array1 = np.zeros(8, np.uint8)
# p1投影的灰度等级(共8个)
for m in range(-4, 4):
for n in range(-4, 4):
p1 = int(gray[i + m, j + n] / 32)
array1[p1] = array1[p1] + 1
# 求最大灰度段l
currentMax = array1[0]
l = 0
for k in range(0, 8):
if currentMax < array1[k]:
currentMax = array1[k]
l = k # 处于k灰度段
# 简化求l灰度段中各通道值 均值(或取均值)
for m in range(-4, 4):
for n in range(-4, 4):
# 灰度等级:32 灰度段:l 处于l灰度段中
if gray[i + m, j + n] >= (l * 32) and gray[i + m, j + n] <= ((l + 1) * 32):
(b, g, r) = img[i + m, j + n]
# 4 颜色封装
dst[i, j] = (b, g, r)
# 5 显示油画效果图
# 较大的图片处理时间较长
cv2.imshow('dst', dst)
cv2.waitKey(0)
油画效果如下: