一、从文件读取图片
cv2.imread(filename, flags)
参数:
filepath:读入image的完整路径
flags:标志位,{cv2.IMREAD_COLOR,cv2.IMREAD_GRAYSCALE,cv2.IMREAD_UNCHANGED}
cv2.IMREAD_COLOR:默认参数,读入一副彩色图片,忽略alpha通道,可用1作为实参替代
cv2.IMREAD_GRAYSCALE:读入灰度图片,可用0作为实参替代
cv2.IMREAD_UNCHANGED:顾名思义,读入完整图片,包括alpha通道,可用-1作为实参替代
PS:alpha通道,又称A通道,是一个8位的灰度通道,该通道用256级灰度来记录图像中的透明度复信息,定义透明、不透明和半透明区域,其中黑表示全透明,白表示不透明,灰表示半透明
二、从内存加载图片
cv2.imdecode(buf, flags)
参数:
buf:通常是numpy.ndarray类型的内存数组
flags:同cv2.imread函数的flags参数
三、保存图片到文件
cv2.imwrite(filename, img,params)
参数:
filename:保存image的完整路径
img:要保存的图像
params:列表参数,比如[cv2.IMWRITE_JPEG_QUALITY,100,cv2.IMWRITE_JPEG_LUMA_QUALITY,10]
四、图片混合
cv2.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]])
参数:
src1:图片1
alpha:图片1权重
src2:图片2
beta:图片2权重
gamma:添加到每个总和的标量。一般为0
dst:输出图片,Python版本不需要指
dtype:输出数组的可选深度,默认即可
五、示例代码
import sys
import cv2
import numpy as np
from my_cv_util import MyCvUtil
class CvSimpleDemo(object):
def __init__(self):
self.img_1 = None
self.img_2 = None
self.alpha = 100
self.beta = 10
@staticmethod
def hello_cv():
img = cv2.imread("yd.jpg", cv2.IMREAD_COLOR)
h, w, d = img.shape
print(h, w, d)
MyCvUtil.show_img_win(img, 'img')
MyCvUtil.set_win_title('img', '你好,opencv')
@staticmethod
def im_decode():
img = cv2.imdecode(np.fromfile('p1.jpg', dtype=np.uint8), cv2.IMREAD_UNCHANGED)
MyCvUtil.show_img_win(img, 'img')
MyCvUtil.set_win_title('img', '从内存加载图片演示')
MyCvUtil.set_win_center('img', 800, 600)
@staticmethod
def im_read_flags():
img = cv2.imread("p1.jpg", cv2.IMREAD_ANYDEPTH)
cv2.imshow("img1", img)
img = cv2.imread("p1.jpg", cv2.IMREAD_COLOR)
cv2.imshow("img2", img)
img = cv2.imread("p1.jpg", cv2.IMREAD_GRAYSCALE)
cv2.imshow("img3", img)
@staticmethod
def im_write():
img = cv2.imread('p1.jpg')
height, width = img.shape[:2] # a[:n] 代表列表中的第一项到第n项
cv2.line(img, (0, 0), (width, height), (0, 0, 255), 2)
cv2.imwrite('im_write.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 95])
img = cv2.imread('im_write.jpg')
cv2.namedWindow("img", cv2.WINDOW_NORMAL)
cv2.imshow("img", img)
@staticmethod
def mutil_pic():
img1 = cv2.imread('1.jpg')
img2 = cv2.imread('2.jpg')
img3 = cv2.imread('3.jpg')
mutil_pic = np.hstack([img1, img2, img3])
# mutil_pic = np.vstack([img1, img2, img3])
cv2.imshow("mutil_pic", mutil_pic)
@staticmethod
def mouse_cb():
def on_mouse_cb(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
cv2.circle(img, (x, y), 20, (255, 255, 255), -1) # thickness: 线宽,-1表示填充
cv2.namedWindow('img')
cv2.setMouseCallback('img', on_mouse_cb)
img = np.zeros((200, 200))
while True:
cv2.imshow('img', img)
n = cv2.waitKey(5)
if n == ord('q'):
break
elif n == ord('s'):
cv2.imwrite("res.jpg", img)
print("保存成功")
def updateAlpha(self, x):
self.alpha = x
self.alpha = self.alpha * 0.01
self.img_1 = np.uint8(np.clip((self.alpha * self.img_2 + self.beta), 0, 255))
def updateBeta(self, x):
self.beta = x
# np.clip()是一个截取函数,用于截取数组中小于或者大于某值的部分,并使得被截取部分等于固定值
self.img_1 = np.uint8(np.clip((self.alpha * self.img_2 + self.beta), 0, 255))
def track_bar(self):
self.img_1 = cv2.imread("test.jpg")
self.img_2 = self.img_1.copy()
cv2.namedWindow('image')
cv2.createTrackbar('Alpha', 'image', 0, 300, self.updateAlpha)
cv2.createTrackbar('Beta', 'image', 0, 255, self.updateBeta)
cv2.setTrackbarPos('Alpha', 'image', 100)
cv2.setTrackbarPos('Beta', 'image', 10)
while True:
cv2.imshow('image', self.img_1)
if cv2.waitKey(10) == ord('q'):
break
@staticmethod
def addWeighted():
img1 = cv2.imread("img1.jpg", cv2.IMREAD_COLOR)
if img1 is None:
sys.exit("Could not read the img1.jpg.")
img2 = cv2.imdecode(np.fromfile("山水.jpg", dtype=np.uint8), cv2.IMREAD_UNCHANGED)
if img2 is None:
sys.exit("Could not read the 山水.jpg.")
alpha = beta = 0.5
dst = cv2.addWeighted(img1, alpha, img2, beta, 0.0, None)
cv2.imshow("dst", dst)
MyCvUtil.set_win_title('dst', '图片混合')
if __name__ == '__main__':
# CvSimpleDemo.hello_cv()
# CvSimpleDemo.im_decode()
# CvSimpleDemo.im_read_flags()
CvSimpleDemo.im_write()
# CvSimpleDemo.mutil_pic()
# CvSimpleDemo.mouse_cb()
# CvSimpleDemo.addWeighted()
cvSimpleDemo = CvSimpleDemo()
cvSimpleDemo.track_bar()
cv2.waitKey(0)
cv2.destroyAllWindows()
六、my_cv_util.py
import cv2
import numpy as np
import win32gui
import pyautogui
from PIL import ImageDraw, ImageFont, Image
class MyCvUtil(object):
@staticmethod
def set_win_title(win_cls_name: str, title: str):
handle = win32gui.FindWindow(0, win_cls_name)
if handle != 0:
win32gui.SetWindowText(handle, title)
@staticmethod
def set_win_center(win_name: str, win_width: int, win_height: int):
cv2.resizeWindow(win_name, win_width, win_height)
screen_size = pyautogui.size()
x = (screen_size.width - win_width) // 2
y = (screen_size.height - win_height) // 2
cv2.moveWindow(win_name, x, y)
@staticmethod
def show_img_win(a_img: np.ndarray, win_name: str):
cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)
h, w = a_img.shape[:2]
MyCvUtil.set_win_center(win_name, w, h)
cv2.imshow(win_name, a_img)
@staticmethod
def draw_text(a_img: np.ndarray, info: str,
fontFace: int = cv2.FONT_HERSHEY_COMPLEX,
fontScale: int = 2, thickness: int = 2,
color=(255, 255, 255)):
text_size = cv2.getTextSize(info, fontFace, fontScale, thickness)
img_h, img_w = a_img.shape[:2]
font_w, font_h = text_size[0]
p_center = ((img_w - font_w) // 2, (img_h - font_h) // 2)
cv2.putText(a_img, info, p_center, fontFace, fontScale, color=color, thickness=thickness)
@staticmethod
def draw_ch_text(a_img, text, position, textColor, textSize):
if isinstance(a_img, np.ndarray):
a_img = Image.fromarray(cv2.cvtColor(a_img, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(a_img)
fontStyle = ImageFont.truetype("msyh.ttc", textSize, encoding="utf-8")
draw.text(position, text, textColor, font=fontStyle)
return cv2.cvtColor(np.asarray(a_img), cv2.COLOR_RGB2BGR)
标签:img,python,win,self,cv2,opencv,np,def,图片
From: https://blog.csdn.net/SilentVoidCan/article/details/140874269