彩色图转为黑白图代码:
'''
#感兴趣区域是黑色
import cv2
import numpy as np
def nothing(x):
pass
def createbars():
cv2.createTrackbar("H_l", "image", 0, 180, nothing)
cv2.createTrackbar("H_h", "image", 0, 180, nothing)
cv2.createTrackbar("S_l", "image", 0, 255, nothing)
cv2.createTrackbar("S_h", "image", 0, 255, nothing)
cv2.createTrackbar("V_l", "image", 0, 255, nothing)
cv2.createTrackbar("V_h", "image", 0, 255, nothing)
cv2.namedWindow("image")
createbars()
lower = np.array([0, 0, 0])
upper = np.array([0, 0, 0])
"""
lower = np.array([25, 95, 65])
upper = np.array([65, 255, 255])
"""
while True:
frame = cv2.imread("F:/mx_matting/test_pic/fengetu/000082_croped83_2.png")
hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower[0] = cv2.getTrackbarPos("H_l", "image")
upper[0] = cv2.getTrackbarPos("H_h", "image")
lower[1] = cv2.getTrackbarPos("S_l", "image")
upper[1] = cv2.getTrackbarPos("S_h", "image")
lower[2] = cv2.getTrackbarPos("V_l", "image")
upper[2] = cv2.getTrackbarPos("V_h", "image")
mask = cv2.inRange(hsv_frame, upper, lower)
cv2.imshow("mask", mask)
cv2.imwrite("F:/mx_matting/test_pic/erzhitu/000082_croped83_2.png", mask)
if cv2.waitKey(0):
break
cv2.destroyAllWindows()
'''
#感兴趣区域是白色
import cv2
# 读取图像
img = cv2.imread('F:/mx_matting/test_pic/fengetu/000006_croped7_2.png')
# 变微灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 大津法二值化
retval, dst = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)
# 腐蚀和膨胀是对白色部分而言的,膨胀,白区域变大,最后的参数为迭代次数
dst = cv2.dilate(dst, None, iterations=1)
# 腐蚀,白区域变小
dst = cv2.erode(dst, None, iterations=4)
cv2.imshow('binary', dst)
cv2.imwrite("F:/mx_matting/test_pic/erzhitu_bai/000006_croped7_2.png", dst)
cv2.waitKey(0)
扣出前景代码:
import cv2
from PIL import Image
import numpy as np
yuantu = "F:/mx_matting/models-master/research/deeplab/datasets/VOCdevkit/VOC2012/JPEGImages/2007_000346.jpg"
masktu = "F:/mx_matting/two_img/2007_000346_out1.jpg"
#使用opencv叠加图片
img1 = cv2.imread(yuantu)
img2 = cv2.imread(masktu)
'''
alpha = 1
meta = 1 - alpha
gamma = 0'''
#cv2.imshow('img1', img1)
#cv2.imshow('img2', img2)
#image = cv2.addWeighted(img1,alpha,img2,meta,gamma)
image = cv2.add(img1, img2)
cv2.imshow('image', image)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
cv2.imwrite("F:/mx_matting/matting/2007_000346_mask.png",image)