繁体   English   中英

如何使一个图像的渐变外观与另一个相同?

[英]How can I make the gradient appearance of one image equal to the other?

我有一个带有阴影外观的图像 A ,我有一个纯色图像 B。 我想将图像 A 的阴影从 Python 中的 OpenCV 复制到图像 B。 如果我没猜错,它与图像的渐变有关吗?

您可以使用 ImageMagick 或 Python Wand 或在 Python/OpenCV 中多做一些努力来轻松做到这一点。

请注意,Python Wand 使用 ImageMagick。

ImageMagick 已经在大多数 Linux 发行版上可用,并且可用于 Windows 和 Mac OSX。

该过程是将图像 B 转换为灰度,然后使用硬光合成方法将其与图像 A 合成。

图一:

图 B:

使用ImageMagick (Unix 语法) ,代码将是:

convert skirt_A.png \
\( skirt_B.png -colorspace gray -level 25x100% \) \
-compose hardlight -composite skirt_A_shaded.png

图像 A 从图像 B 着色:

更改级别操作符中的 0.25 以使阴影更暗或更亮。

使用Python Wand代码将是:

from wand.image import Image
from wand.display import display

with Image(filename='skirt_A.png') as bimg:
    with Image(filename='skirt_B.png') as fimg:
        fimg.transform_colorspace('gray')
        fimg.level(black=0.25,white=1,channel='all_channels')
        bimg.composite_channel('all_channels', fimg, 'hard_light', 0, 0)
        bimg.save(filename='skirt_A_shaded.png')
        display(bimg)

图像 A 从图像 B 着色:

使用Python/OpenCV ,代码将是:

import cv2
import numpy as np

# read image_A and convert to float in range 0 to 1
image_A = cv2.imread('skirt_A.png').astype("float32") / 255.0

# read image_B as grayscale and convert to float in range 0 to 1
image_B = cv2.imread('skirt_B.png',0).astype("float32") / 255.0

# convert image_B from grayscale to 3 equal channels as rgb so that the image multiplication in the hard light compositing will work properly
image_B = cv2.cvtColor(image_B,cv2.COLOR_GRAY2RGB) 

# apply linear transform to stretch image_B to make shading darker
# y = A*x+B
# x=1 -> y=1; x=0.25 -> y=0
# 1 = A + B
# 0 = 0.25*A + B
# Solve simultaneous equations to get:
# A = 1.33
# B = -0.33
image_B = 1.33 * image_B -0.33

# threshold image_B and invert
thresh = cv2.threshold(image_B,0.5,1,cv2.THRESH_BINARY)[1]
thresh_inv = 1-thresh

# do hard light composite and convert to uint8 in range 0 to 255
# see CSS specs at https://www.w3.org/TR/compositing-1/#blendinghardlight
low = 2.0 * image_A * image_B
high = 1 - 2.0 * (1-image_A) * (1-image_B)
result = ( 255 * (low * thresh_inv + high * thresh) ).clip(0, 255).astype(np.uint8)

# show results
cv2.imshow('Result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save results
cv2.imwrite('skirt_A_shaded.png', result)

图像 A 从图像 B 着色:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM