原始图片:
彩色图片灰度化
方式1:import cv2 # 导入cv库
img = cv2.imread('image2.jpg',0)
cv2.imwrite('gray_image.jpg',img)
方式2:import cv2
img = cv2.imread('image2.jpg',1)
dst = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)# 颜色空间转换 1 data 2 BGR gray
cv2.imshow('dst',dst)
方式3#方法4 gray = r*0.299+g*0.587+b*0.114
import cv2
import numpy as np
img = cv2.imread('image0.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
dst = np.zeros((height,width,3),np.uint8)
for i in range(0,height):
for j in range(0,width):
(b,g,r) = img[i,j]
b = int(b)
g = int(g)
r = int(r)
gray = r*0.299+g*0.587+b*0.114
dst[i,j] = np.uint8(gray)
cv2.imshow('dst',dst)
马赛克
import cv2 # 导入cv库 |
边缘检测
方式1:import cv2
import numpy as np
import random
img = cv2.imread('image2.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
#cv2.imshow('src',img)
#canny 1 gray 2 高斯 3 canny
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgG = cv2.GaussianBlur(gray,(3,3),0)
dst = cv2.Canny(img,50,50) #图片卷积——》th
#cv2.imshow('dst',dst)
cv2.imwrite('canny.jpg',dst)
方式2:import cv2
import numpy as np
import random
import math
img = cv2.imread('image2.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 > 50:
dst[i, j] = 255
else:
dst[i, j] = 0
cv2.imwrite('sobel.jpg',dst)
颜色风格变化
import cv2 |
油画特效
import cv2 |
线段绘制
import cv2 |
绘制矩形、圆形
import cv2 |
添加文字
import cv2 |