# 读取图像
imgobj = cv2.imread("img.png")
# 创建窗口名字为img
cv2.namedwindow("img")
# 显示图像
cv2.imshow("img",imgobj)
# 等待事件触发,参数0表示永久等待
cv2.waitkey(0)
释放窗口
cv2.destroyAllwindows()
画出一个直方图数据图:
if __name__ == '__main__':
img1 = cv2.imread('p1.jpg')
hist1 = cv2.calcHist([img1],[0],None,[256],[0.0,255.0])
pyplot.plot(range(256),hist1,'r')
pyplot.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
取背景相同的图的logo:先把图片转成灰度图
from PIL import Image
im = Image.open("222.png").convert('RGBA')
pixdata = im.load()
for y in range(im.size[1]):
for x in range(im.size[0]):
if pixdata[x,y][0] > 200 and pixdata[x,y][1] > 200 and pixdata[x,y][2] > 200 and pixdata[x,y][3]:
pixdata[x,y]= (255, 255, 255, 0)
im.save("3333333.png")
取背景图不同的logo:
import cv2
import numpy as np
# Step1. 加载图像
img = cv2.imread('D:\\untitled\\aa\\aa.png')
# Step2. 创建掩模、背景图和前景图
mask = np.zeros(img.shape[:2], np.uint8) # 创建大小相同的掩模
bgdModel = np.zeros((1,65), np.float64) # 创建背景图像
fgdModel = np.zeros((1,65), np.float64) # 创建前景图像
# Step3. 初始化矩形区域
# 这个矩形必须完全包含前景(相当于这里的梅西)
# rect = (50,50,450,290)
# rect = (275, 120, 170, 320)
rect = (1,1,350,300)
# Step4. GrubCut算法,迭代5次
# mask的取值为0,1,2,3
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT) # 迭代5次
# Step5. mask中,值为2和0的统一转化为0, 1和3转化为1
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
img = img * mask2[:,:,np.newaxis] # np.newaxis 插入一个新维度,相当于将二维矩阵扩充为三维
# cv2.imshow("dst", img)
cv2.waitKey(0)
cv2.imwrite(r"D:\untitled\aa\d.png",img)
convert函数:
值为1:为二值图像,非黑即白,0表示黑,255表示白
值为L:为灰度图
计算两张图的相似度:
import numpy as np
import cv2
from matplotlib import pyplot
# 最简单的以huidu直方图作为相似比较的实现
def classify_gray_hist(image1, image2, size=(256, 256)):
# 先调整大小
image1 = cv2.resize(image1, size)
image2 = cv2.resize(image2, size)
hist1 = cv2.calcHist([image1], [0], None, [256], [0.0, 255.0])
hist2 = cv2.calcHist([image2], [0], None, [256], [0.0, 255.0])
# 比较直方图
pyplot.plot(range(256), hist1, 'r')
pyplot.plot(range(256), hist2, 'y')
pyplot.show()
# 计算直方图的重合度
degree = 0
for i in range(len(hist1)):
if hist1[i] != hist2[i]:
degree = degree + (1 - (abs(hist1[i] - hist2[i]) / max(hist1[i], hist2[i])))
else:
degree = degree + 1
degree = degree / len(hist1)
return degree
def classify_hist_with_split(image1, image2, size=(256, 256)):
# 将图像resize后,分类为三个通道,再计算每个通道的相似值
image1 = cv2.resize(image1, size)
image2 = cv2.resize(image2, size)
sub_image1 = cv2.split(image1)
sub_image2 = cv2.split(image2)
sub_data = 0
for im1, im2 in zip(sub_image1, sub_image2):
sub_data += calculate(im1, im2)
sub_data = sub_data / 3
return sub_data
def calculate(im1, im2):
hist1 = cv2.calcHist([im1], [0], None, [256], [0.0, 255.0])
hist2 = cv2.calcHist([im2], [0], None, [256], [0.0, 255.0])
pyplot.plot(range(256), hist1, 'r')
pyplot.plot(range(256), hist2, 'y')
pyplot.show()
degree = 0
for i in range(len(hist1)):
if hist1[i] != hist2[i]:
degree = degree + (1 - (abs(hist1[i] - hist2[i]) / max(hist1[i], hist2[i])))
else:
degree = degree + 1
degree = degree / len(hist1)
return degree
# 平均哈希算法计算
def classify_aHash(image1, image2):
image1 = cv2.resize(image1, (8, 8))
image2 = cv2.resize(image2, (8, 8))
gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) # 切换至灰度图
gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
hash1 = getHash(gray1)
hash2 = getHash(gray2)
return Hamming_distance(hash1, hash2)
def classify_pHash(image1, image2):
image1 = cv2.resize(image1, (32, 32))
image2 = cv2.resize(image2, (32, 32))
gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) # 切换至灰度图
gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
# 将灰度图转为浮点型,再进行dct变换
dct1 = cv2.dct(np.float32(gray1))
dct2 = cv2.dct(np.float32(gray2))
# 取左上角的8*8,这些代表图片的最低频率
# 这个操作等价于c++中利用opencv实现的掩码操作
# 在python中进行掩码操作,可以直接这样取出图像矩阵的某一部分
dct1_roi = dct1[0:8, 0:8]
dct2_roi = dct2[0:8, 0:8]
print(dct1)
hash1 = getHash(dct1_roi)
hash2 = getHash(dct2_roi)
return Hamming_distance(hash1, hash2)
# 输入灰度图,返回hash
def getHash(image):
avreage = np.mean(image) # 计算像素平均值
hash = []
for i in range(image.shape[0]):
for j in range(image.shape[1]):
if image[i, j] > avreage:
hash.append(1)
else:
hash.append(0)
return hash
# 计算汉明距离
def Hamming_distance(hash1, hash2):
num = 0
for index in range(len(hash1)):
if hash1[index] != hash2[index]:
num += 1
return num
# 差值感知算法
def dhash(image1, image2):
image1 = cv2.resize(image1, (9, 8))
image2 = cv2.resize(image2, (9, 8))
gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) # 切换至灰度图
gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
hash1 = dhashcaulate(gray1)
hash2 = dhashcaulate(gray2)
return Hamming_distance(hash1, hash2)
def dhashcaulate(gray):
hash_str = ''
for i in range(8):
for j in range(8):
if gray[i, j] > gray[i, j + 1]:
hash_str = hash_str + '1'
else:
hash_str = hash_str + '0'
return hash_str
if __name__ == '__main__':
imgobj1 = cv2.imread('aa.png')
imgobj2 = cv2.imread('bb.png')
cv2.imshow('img1', imgobj1)
cv2.imshow('img2', imgobj2)
# 测试两张图片的相似度
degree = classify_gray_hist(imgobj1,imgobj2) #单通道直方图
# degree = classify_hist_with_split(imgobj1,imgobj2) #三通道直方图
# 测试指纹的相似度
# degree = classify_aHash(imgobj1,imgobj2) #平均哈希法
# degree = classify_pHash(imgobj1,imgobj2) #感知哈希法
# degree = dhash(imgobj1, imgobj2) # 差值感知哈希法
print(degree)
cv2.waitKey(0)
使用face_recognition.face_locations(image)返回的数据(y,w,h,x)
用cv2.rectangle(img,(x,y),(w,h),(0,0,255),3)就能截出人脸
代码:
import face_recognition
import cv2
image = face_recognition.load_image_file("test.jpg")
face_locations = face_recognition.face_locations(image)
print(face_locations)
img = cv2.imread("test.jpg")
cv2.rectangle(img,(278,113),(353,188),(0,0,255), 3)
cv2.rectangle(img,(face_locations[0][3],face_locations[0][0]),(face_locations[0][1],face_locations[0][2]),(0,0,255),3)
cv2.namedWindow("sss")
cv2.imshow("sss",img)
cv2.waitKey(0)
cv2.imwrite(r"D:\untitled\test\aaaaaaaaaaaa.jpg",img)