原文链接: opencv 仿照 张靓颖 《Body First》 制作艺术视频
上一篇: opencv 二值化的素描
下一篇: numpy tile 和 opencv repeat 堆叠操作 点阵
https://space.bilibili.com/21808504
思想
将转换为素描的图片和背景图片进行与操作,找到两张图片的交点
将交点部分色素调暗即可
背景
加入内容
完整代码
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
WHITE = 255
DEEP = 155
LIGHT = 180
# rgb 转 gray 转素描格式 0-255
def parse(frame):
img_gray = cv.cvtColor(frame, cv.COLOR_RGB2GRAY)
img_blurred = cv.GaussianBlur(img_gray, (5, 5), 0)
img_threshold1 = cv.adaptiveThreshold(img_blurred, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 5, 2)
img_threshold1_blurred = cv.GaussianBlur(img_threshold1, (5, 5), 0)
_, img_threshold2 = cv.threshold(img_threshold1_blurred, 200, 255, cv.THRESH_BINARY)
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
img_opening = cv.bitwise_not(cv.morphologyEx(cv.bitwise_not(img_threshold2), cv.MORPH_OPEN, kernel))
img_opening_blurred = cv.GaussianBlur(img_opening, (3, 3), 0)
return img_opening_blurred
# rgb 格式的 img 和 bg
# 返回 合成图,大小和bg一样 返回 灰度图
def merge(img, bg):
img = parse(img)
bg = cv.cvtColor(bg, cv.COLOR_RGB2GRAY)
bg[bg < 220] = LIGHT
bg[bg > 220] = WHITE
# plt.hist(bg.flatten(), bins=255, range=(0, 255))
# plt.show()
img = cv.resize(img, bg.shape[::-1])
# 捕获黑线线条
mask_img = img <= LIGHT
mask_bg = bg == LIGHT
mask = np.logical_and(mask_img, mask_bg)
bg[mask] = DEEP
return bg
def parse_video(video_path):
capture = cv.VideoCapture(video_path)
bg = cv.imread('./bg.jpg')
fourcc = cv.VideoWriter_fourcc(*"mp4v")
size = bg.shape[:2][::-1]
print('size', size) # (1080, 1920)
out_file = cv.VideoWriter("./out.mp4", fourcc, 30, (1920, 1080))
while capture.isOpened():
ret, frame = capture.read()
if not ret:
break
out = merge(frame, bg)
out = cv.cvtColor(out, cv.COLOR_GRAY2BGR)
out_file.write(out)
out_file.release()
def main():
parse_video('./video/cxk.mp4')
# bg = cv.imread('./bg.jpg')
# img = cv.imread('./img/cxk.jpg')
#
# out = merge(img, bg)
# # plt.imshow(out, cmap='gray')
# # plt.show()
# plt.hist(out.flatten(), bins=255, range=(0, 255))
# plt.show()
#
# cv.imshow("out", out)
# cv.imwrite('./out.jpg', out)
# cv.waitKey()
if __name__ == '__main__':
main()