敞开成长之旅!这是我参加「日新计划 12 月更文挑战」的第9天,点击查看活动概况
最近处理视觉相关的项目,共享一下经过opencv的图画特效处理,
原图镇楼
1、灰度处理
将cv2.imread()办法的第二参数设为0即可得到灰色图画。
import cv2
img0 = cv2.imread('1.jpg', 0)
img1 = cv2.imread('1.jpg', 1)
print(img0.shape)
print(img1.shape)
cv2.imshow('img0', img0)
cv2.waitKey(0)
经过cv2.cvtColor
办法对图画进行灰度转化
cv2.cvtColor(src, code, dst, dstCN):
-src: 目标图画-code: 色彩转化方法-dst: 图画巨细-dstCN:色彩通道巨细
import cv2
img = cv2.imread('1.jpg', 1)
dat = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY )
cv2.imshow('dat', dat)
cv2.waitKey(0)
灰色图画的所有色彩通道的值相等,所以要想将五颜六色图画变为灰色图画,只需将他们色彩通道的值相等即可。
经过设置图片的色彩均值来使五颜六色图画变为灰色图画
import cv2
import numpy as np
img = cv2.imread('1.jpg', 1)
dat = np.zeros((img.shape[0], img.shape[1]), np.uint8)
for i in range(0, img.shape[0]):
for j in range(0, img.shape[1]):
(b, g, r) = img[i, j]
gray = (int(b) + int(g) + int(r)) / 3
dat[i, j] = np.uint(gray)
cv2.imshow('dat', dat)
cv2.waitKey(0)
2、色彩回转
将图画的色彩回转也就是让255减去当前的色彩值
import cv2
import numpy as np
img = cv2.imread('1.jpg', 1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
dat = np.zeros((img.shape[0], img.shape[1]), np.uint8)
for i in range(gray.shape[0]):
for j in range(gray.shape[1]):
dat[i, j] = 255 - gray[i, j]
cv2.imshow('dat', dat)
cv2.waitKey(0)
五颜六色图画的色彩回转也是一样的道理
import cv2
import numpy as np
img = cv2.imread('1.jpg', 1)
dat = np.zeros((img.shape[0], img.shape[1], img.shape[2]), np.uint8)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
(b, g, r) = img[i, j]
dat[i, j] = (255 - b, 255 - g, 255 - r)
cv2.imshow('src', img)
cv2.imshow('dat', dat)
cv2.waitKey(0)
3、马赛克
原理: 取一个指定巨细的窗口,将该窗口填充为一个色彩
下面将窗口设置为10*10来生成一个马赛克图画
import cv2
img = cv2.imread('1.jpg', 1)
height = img.shape[0]
width = img.shape[1]
for m in range(100, 200):
for n in range(200, 300):
if m % 10 == 0 and n % 10 == 0:
for i in range(10):
for j in range(10):
(b, g, r) = img[m, n]
img[m + i, n + j] = (b, g, r)
cv2.imshow('img', img)
cv2.waitKey(0)
4、毛玻璃效果
原理: 将当前的像素色彩随机设置为窗口中的一个色彩
这里设置窗口为8*8来生成一个毛玻璃图画
import cv2
import random
import numpy as np
img = cv2.imread('1.jpg', 1)
height = img.shape[0]
width = img.shape[1]
dat = np.zeros(img.shape, np.uint8)
for m in range(height - 8):
for n in range(width - 8):
index = int(random.random() * 8)
(b, g, r) = img[m + index, n + index]
dat[m, n] = (b, g, r)
cv2.imshow('dat', dat)
cv2.waitKey(0)
5、图画交融
图片乘以份额系数相加得到俩张图片的交融效果,公式如下
target=src1*a+src2*(1-a)
cv2.addWeighted(src1, alpha, src2, beta, gamma):
import cv2
import numpy as np
img1 = cv2.imread('1.jpg', 1)
img2 = cv2.imread("2.jpg", 1)
img3 = cv2.resize(img2, (img1.shape[1], img1.shape[0]), interpolation=cv2.INTER_AREA)
dat = np.zeros(img1.shape, np.uint8)
dat = cv2.addWeighted(img1, 0.8, img3, 0.2, 0)
cv2.imshow('dat', dat)
cv2.waitKey(0)