实现图片中划线并保存
python
复制代码
import cv2
def draw_test(event,x,y,flag,param):
global drawing
# cv2.EVENT_LBUTTONDOWN 鼠键左键按下事件
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
# cv2.EVENT_MOUSEMOVE 鼠键左键移动事件
elif event == cv2.EVENT_MOUSEMOVE:
if drawing:
cv2.circle(img,(x,y),15,(255,0,0),-1)
#cv2.EVENT_LBUTTONUP 鼠键左键释放事件
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
cv2.circle(img, (x, y), 15, (255, 0, 0), -1)
img= cv2.imread('images/car.png')
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_test)
# 真正的标志,表示是否正在绘制
drawing = False
while(True):
cv2.imshow('image', img)
if cv2.waitKey(20) == 115:
rs = cv2.imwrite("save_image/car1.png", img)
if cv2.waitKey(20) == 27: # 按ESC退出
break
cv2.destroyAllWindows()
实现摄像头捕捉和文本显示且鼠标点击文本中的数字加一
python
复制代码
import cv2
from PIL import Image, ImageDraw, ImageFont
import numpy as np
def put_text(image, text, position, font_path, font_size, color):
pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(pil_image)
font = ImageFont.truetype(font_path, font_size)
draw.text(position, text, fill=color, font=font)
image_with_text = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
return image_with_text
cap = cv2.VideoCapture(0)
cv2.namedWindow("name", cv2.WINDOW_NORMAL)
cv2.resizeWindow("name", 500, 300)
rocket_count = 0
def draw_test(event, x, y, flags, param):
global rocket_count
if event == cv2.EVENT_LBUTTONDOWN:
rocket_count += 1
cv2.setMouseCallback("name", draw_test)
while True:
ret, frame = cap.read()
if ret:
text = f"老铁们,火箭刷起来,你已刷个{rocket_count}火箭"
position = (0, 50)
font_path = "simhei.ttf"
font_size = 25
color = (255, 0, 0)
frame = put_text(frame, text, position, font_path, font_size, color)
cv2.imshow("name", frame)
if cv2.waitKey(20) == 27:
break
cap.release()
cv2.destroyAllWindows()