# -*- coding: utf-8 -*-
"""
Created on Tue Apr 20 15:30:26 2021
@author: xf
"""
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
#图片名
picture_name = "bizhi1.jpg"
#图片路径
path = r"F:\pypicture"
# 生成图片
img = cv2.imread(path + "\\" +picture_name)
# 生成灰色图片
imgGrey = cv2.imread(path + "\\" +picture_name, 0)
# 展示原图
# cv2.imshow("img", img)
# 展示灰色图片
# cv2.imshow("imgGrey", imgGrey)
# 等待图片的关闭
#cv2.waitKey()
# 保存灰色图片
cv2.imwrite(path + "\\" +"Copy.jpg", imgGrey)
# =============================================================================
# img.shape 返回图像高(图像矩阵的行数)、宽(图像矩阵的列数)和通道数3个属性组成的元组,
# 若图像是非彩色图,则只返回高和宽组成的元组。
# =============================================================================
# sp1 = img.shape
# sp2 = imgGrey.shape
# print(sp1)
# print(sp2)
# =============================================================================
# 在图片上写字
# =============================================================================
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
if (isinstance(img, np.ndarray)): # 判断是否OpenCV图片类型
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
# 创建一个可以在给定图像上绘图的对象
draw = ImageDraw.Draw(img)
# 字体的格式
fontStyle = ImageFont.truetype(
"simsun.ttc", textSize, encoding="utf-8")
# 绘制文本
draw.text((left, top), text, textColor, font=fontStyle)
# 转换回OpenCV格式
return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
# img = cv2ImgAddText(img, "离谱", 500, 500, (255, 0 , 0), 100)
# cv2.imshow("img",img)
# cv2.waitKey()
# cv2.imwrite(path + "\\" +"CopyWrite.jpg",img)
# =============================================================================
# 缩放使用cv2.resize()函数,resize函数里的size第一个是宽(列),第二个是高(行)。
# =============================================================================
# imgg = cv2.resize(img, (200, 100))
# cv2.imshow("imgg", imgg)
# cv2.waitKey()