Python 如何在使用cv2混合2幅图像时移除光影边界?
我曾尝试使用cv2将两幅图像混合在一起,但得到了不同颜色的奇怪边框。 结果图像在明暗区域之间有奇怪的黄色边界。我怎样才能删除它? 这是我用来将它们混合在一起的代码:Python 如何在使用cv2混合2幅图像时移除光影边界?,python,image,opencv,cv2,alphablending,Python,Image,Opencv,Cv2,Alphablending,我曾尝试使用cv2将两幅图像混合在一起,但得到了不同颜色的奇怪边框。 结果图像在明暗区域之间有奇怪的黄色边界。我怎样才能删除它? 这是我用来将它们混合在一起的代码: land = cv2.imread(land_path) land = cv2.cvtColor(land, cv2.COLOR_BGR2RGB) land = land.astype(float) h, w, c = land.shape sky = cv2.imread(sky_path) sky = cv2.cvtColor
land = cv2.imread(land_path)
land = cv2.cvtColor(land, cv2.COLOR_BGR2RGB)
land = land.astype(float)
h, w, c = land.shape
sky = cv2.imread(sky_path)
sky = cv2.cvtColor(sky, cv2.COLOR_BGR2RGB)
sky = cv2.resize(sky, (w, h))
sky = sky.astype(float)
mask = cv2.imread(mask_path)
mask = cv2.resize(mask, (w, h))
mask = mask.astype(float)/255
sky = cv2.multiply(mask, sky)
land = cv2.multiply(1.0 - mask, land)
result = cv2.add(sky, land)
cv2.imwrite(result_path, result[:, :, ::-1])
原始图像:
我得到的结果是:
试着去除月球周围的黑暗区域。在Python/OpenCV中添加类似于
mask[mask的内容是一种方法。你的问题是你正在使用的掩码。它应该来自天空图像,以避免地平线上方区域的衰减。当你的掩码中地平线上方的明亮区域被抵消时,会导致日落的衰减,使你看到黑暗区域
- Read the land and sky images
- Make a version of the sky image as gray
- Convert both the float
- Threshold the gray sky image and antialias by blurring and making black anything below 128.
- Convert mask to float in range 0 to 1 and make it 3 channels.
- Do the blending
- Save the result
土地形象:
天空图像:
导入cv2
将numpy作为np导入
#读取陆地图像并转换为浮动
land=cv2.imread(“land.jpg”)
land=land.astype(np.32)
h、 w,c=陆地形状
#读取天空图像,裁剪为与前一图像相同的大小,将副本转换为灰色,将天空图像转换为浮动
sky=cv2.imread(“sky.jpg”)
天空=天空[0:h,0:w]
灰色天空=cv2.CVT颜色(天空,cv2.COLOR\u BGR2GRAY)
sky=sky.astype(np.float32)
#通过对天空图像进行阈值化制作遮罩,抗锯齿,转换为0到1范围内的浮动,并制作3个通道
mask=cv2.threshold(灰色天空,0,255,cv2.THRESH\u二进制+cv2.THRESH\u大津)[1]
掩模=cv2.高斯模糊(掩模,(0,0),3,3)
遮罩[mask]遮罩不是完全黑白的,因此原始图像中的淡黄色天空会混合到最终图像中。通过对遮罩进行二值化,可能会获得更好的效果
import cv2
import numpy as np
# read land image and convert to float
land = cv2.imread("land.jpg")
land = land.astype(np.float32)
h, w, c = land.shape
# read sky image, crop to same size as previous image, convert copy to gray, convert sky image to float
sky = cv2.imread("sky.jpg")
sky = sky[0:h, 0:w]
gray_sky = cv2.cvtColor(sky, cv2.COLOR_BGR2GRAY)
sky = sky.astype(np.float32)
# make mask by thresholding sky image, antialias, convert to float in range 0 to 1 and make 3 channels
mask = cv2.threshold(gray_sky, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
mask = cv2.GaussianBlur(mask, (0,0), 3, 3)
mask[mask<128] = 0
mask = mask.astype(np.float32)/255
mask = cv2.merge([mask,mask,mask])
# blend and convert back to 8-bit result
result = land * (1 - mask) + sky * mask
result = result.clip(0,255).astype(np.uint8)
# save result
cv2.imwrite("land_sky.jpg", result)
# show results
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()