在矩形中绘制图像 python
Draw image in rectangle python
我已经使用 matplotlib 绘制了一个矩形,并想在其中放置一个图像,如下图所示。有谁知道我如何在 python 中实现这一点?
您可以使用 imshow
将图像放置在给定位置。并添加一个变换,使图像具有与矩形相同的旋转。
为了避免可能的版权问题,以下代码使用了来自 wikipedia(作者:Fernando Revilla)的图片:
import matplotlib.pyplot as plt
from matplotlib import transforms
from matplotlib.patches import Rectangle
file = 'https://upload.wikimedia.org/wikipedia/commons/thumb/8/82/Giant_Panda_Tai_Shan.JPG/1200px-Giant_Panda_Tai_Shan.JPG'
img = plt.imread(file, format='jpg')
fig, ax = plt.subplots()
# suppose a rectangle was drawn onto the plot
x, y = 20, 30
width, height = 12, 9
angle = 70
rect = Rectangle((x, y), width, height, angle=angle, ec='black', fc='none', lw=3)
ax.add_patch(rect)
# draw the image using the rectangles position and rotation
tr = transforms.Affine2D().translate(-x, -y).rotate_deg(angle).translate(x, y)
ax.imshow(img, extent=[x, x + width, y, y + height], transform=tr + ax.transData)
ax.set_aspect('equal') # keep right angles
ax.relim()
ax.autoscale()
plt.show()
这是使用 Python/OpenCV/Numpy 的一种方法。使用熊猫图像的 4 个角和矩形的 4 个角对熊猫图像进行透视变形。然后制作多余区域的蒙版,这些区域在变形图像中为黑色。最后,使用蒙版混合变形图像和背景图像。
输入:
图形图像:
import numpy as np
import cv2
import math
# read image to be processed
img = cv2.imread("panda.png")
hh, ww = img.shape[:2]
# read background image
bck = cv2.imread("rectangle_graph.png")
hhh, www = bck.shape[:2]
# specify coordinates for corners of img in order TL, TR, BR, BL as x,y pairs
img_pts = np.float32([[0,0], [ww-1,0], [ww-1,hh-1], [0,hh-1]])
# manually pick coordinates of corners of rectangle in background image
bck_pts = np.float32([[221,245], [333,26], [503,111], [390,331]])
# compute perspective matrix
matrix = cv2.getPerspectiveTransform(img_pts,bck_pts)
#print(matrix)
# change black and near-black to graylevel 1 in each channel so that no values
# inside panda image will be black in the subsequent mask
img[np.where((img<=[5,5,5]).all(axis=2))] = [1,1,1]
# do perspective transformation setting area outside input to black
img_warped = cv2.warpPerspective(img, matrix, (www,hhh), cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0,0,0))
# make mask for area outside the warped region
# (black in image stays black and rest becomes white)
mask = cv2.cvtColor(img_warped, cv2.COLOR_BGR2GRAY)
mask = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)[1]
mask = cv2.merge([mask,mask,mask])
mask_inv = 255 - mask
# use mask to blend between img_warped and bck
result = ( 255 * (bck * mask_inv + img_warped * mask) ).clip(0, 255).astype(np.uint8)
# save images
cv2.imwrite("panda_warped.png", img_warped)
cv2.imwrite("panda_warped_mask.png", mask)
cv2.imwrite("panda_in_graph.png", result)
# show the result
cv2.imshow("warped", img_warped)
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
扭曲的输入:
掩码:
结果:
我已经使用 matplotlib 绘制了一个矩形,并想在其中放置一个图像,如下图所示。有谁知道我如何在 python 中实现这一点?
您可以使用 imshow
将图像放置在给定位置。并添加一个变换,使图像具有与矩形相同的旋转。
为了避免可能的版权问题,以下代码使用了来自 wikipedia(作者:Fernando Revilla)的图片:
import matplotlib.pyplot as plt
from matplotlib import transforms
from matplotlib.patches import Rectangle
file = 'https://upload.wikimedia.org/wikipedia/commons/thumb/8/82/Giant_Panda_Tai_Shan.JPG/1200px-Giant_Panda_Tai_Shan.JPG'
img = plt.imread(file, format='jpg')
fig, ax = plt.subplots()
# suppose a rectangle was drawn onto the plot
x, y = 20, 30
width, height = 12, 9
angle = 70
rect = Rectangle((x, y), width, height, angle=angle, ec='black', fc='none', lw=3)
ax.add_patch(rect)
# draw the image using the rectangles position and rotation
tr = transforms.Affine2D().translate(-x, -y).rotate_deg(angle).translate(x, y)
ax.imshow(img, extent=[x, x + width, y, y + height], transform=tr + ax.transData)
ax.set_aspect('equal') # keep right angles
ax.relim()
ax.autoscale()
plt.show()
这是使用 Python/OpenCV/Numpy 的一种方法。使用熊猫图像的 4 个角和矩形的 4 个角对熊猫图像进行透视变形。然后制作多余区域的蒙版,这些区域在变形图像中为黑色。最后,使用蒙版混合变形图像和背景图像。
输入:
图形图像:
import numpy as np
import cv2
import math
# read image to be processed
img = cv2.imread("panda.png")
hh, ww = img.shape[:2]
# read background image
bck = cv2.imread("rectangle_graph.png")
hhh, www = bck.shape[:2]
# specify coordinates for corners of img in order TL, TR, BR, BL as x,y pairs
img_pts = np.float32([[0,0], [ww-1,0], [ww-1,hh-1], [0,hh-1]])
# manually pick coordinates of corners of rectangle in background image
bck_pts = np.float32([[221,245], [333,26], [503,111], [390,331]])
# compute perspective matrix
matrix = cv2.getPerspectiveTransform(img_pts,bck_pts)
#print(matrix)
# change black and near-black to graylevel 1 in each channel so that no values
# inside panda image will be black in the subsequent mask
img[np.where((img<=[5,5,5]).all(axis=2))] = [1,1,1]
# do perspective transformation setting area outside input to black
img_warped = cv2.warpPerspective(img, matrix, (www,hhh), cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0,0,0))
# make mask for area outside the warped region
# (black in image stays black and rest becomes white)
mask = cv2.cvtColor(img_warped, cv2.COLOR_BGR2GRAY)
mask = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)[1]
mask = cv2.merge([mask,mask,mask])
mask_inv = 255 - mask
# use mask to blend between img_warped and bck
result = ( 255 * (bck * mask_inv + img_warped * mask) ).clip(0, 255).astype(np.uint8)
# save images
cv2.imwrite("panda_warped.png", img_warped)
cv2.imwrite("panda_warped_mask.png", mask)
cv2.imwrite("panda_in_graph.png", result)
# show the result
cv2.imshow("warped", img_warped)
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
扭曲的输入:
掩码:
结果: