使用 Python 更改图像的形状以采用封闭图像的形状 [英] Altering the shape of an image to take the shape of an enclosed image with Python

查看:84
本文介绍了使用 Python 更改图像的形状以采用封闭图像的形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手.我想扭曲第一个图像,使其填充第二个图像的闭合路径.我有两个图像.一个是源图像,另一个是封闭图像.是否可以在任何类型的封闭路径内填充图像.您能否建议使用 Python 库,或者如果您可以共享一些代码,那就太好了.我还尝试使用角点检测算法并使它们坚持使用地图功能,但我不能.

I am new to Python. I would like to warp the first image such that it fills the closed path of the second image. I have two images. One is the source image and the other is an enclosed image. Is it possible to fill the image within any kind of closed path. Can you please suggest Python libraries to be used or it'd be great if you can share some code. I was also trying to work with corner detection algorithms and making them to stick with map function, but I can't.

两张图片和我期望得到的最终结果:

Two images and the end result which I'm expecting to get:

推荐答案

以下是使用 Python/OpenCV 使用蒙版将一个图像叠加到另一个图像上的示例.

Here is an example of overlaying one image onto another using a mask with Python/OpenCV.

T 恤图片:

图案图像:

T 恤面具图片:

 - Read the 3 images and get shapes
 - Convert the mask to gray and binarize
 - Resize the pattern so that its smallest dimension is the size of the largest dimension of the tshirt image
 - Crop it to exactly the same size as the tshirt image
 - Apply the mask to the pattern image
 - Apply the inverse mask to the tshirt image
 - Add the two together
 - Save the results


import cv2
import numpy as np

# read shirt image and get its max dimension
img = cv2.imread('tshirt.jpg')
hh, ww = img.shape[:2]
maxwh = max(hh, ww)

# read pattern image and get its size and minimum dimension
pattern = cv2.imread('tshirt_pattern.jpg')
ht, wd = pattern.shape[:2]
minwh = min(ht,wd)

# read shirt mask image
maskimg = cv2.imread('tshirt_mask.png')

# convert mask to gray and binarize
maskimg = cv2.cvtColor(maskimg, cv2.COLOR_BGR2GRAY)
maskimg = cv2.threshold(maskimg, 128, 255, cv2.THRESH_BINARY)[1]

# resize pattern so minimum dimension is size of largest dimension of tshirt image
scale = maxwh/minwh
pattern_enlarge = cv2.resize(pattern, dsize=(0,0), fx=scale, fy=scale)

# limit resized pattern to size of tshirt
pattern_enlarge = pattern_enlarge[0:hh, 0:ww]

# do masked overlay
pattern_masked = cv2.bitwise_and(pattern_enlarge, pattern_enlarge, mask=maskimg)
img_masked = cv2.bitwise_and(img, img, mask=(255-maskimg))
result = cv2.add(img_masked, pattern_masked)

cv2.imshow('image', img)
cv2.imshow('pattern', pattern)
cv2.imshow('mask', maskimg)
cv2.imshow('masked pattern', pattern_masked)
cv2.imshow('masked image', img_masked)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save results
cv2.imwrite('tshirt_masked.jpg', img_masked)
cv2.imwrite('pattern_masked.jpg', pattern_masked)
cv2.imwrite('tshirt_pattern_overlay.jpg', result)


蒙版图案图像:


masked pattern image:

蒙面 T 恤图片:

结果图像:

这篇关于使用 Python 更改图像的形状以采用封闭图像的形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆