![](/img/trans.png)
[英]How do I make a rectangular sprite stop when it collides with another rectangular sprite using pygame?
[英]How do I make rectangular image squared using OpenCV and Python?
我有各種各樣的矩形圖像。 我需要將它們修改為統一的方形(不同大小可以)。
為此,我必須將它放在較大的方形之上。 背景為黑色。
當我需要對 2 個圖像進行分層時,我想到了這一點:
import cv2
import numpy as np
if 1:
img = cv2.imread(in_img)
#get size
height, width, channels = img.shape
print (in_img,height, width, channels)
# Create a black image
x = height if height > width else width
y = height if height > width else width
square= np.zeros((x,y,3), np.uint8)
cv2.imshow("original", img)
cv2.imshow("black square", square)
cv2.waitKey(0)
如何將它們堆疊在一起,使原始圖像垂直和水平居中在黑色形狀的頂部?
我想通了。 你需要“廣播成型”:
square[(y-height)/2:y-(y-height)/2, (x-width)/2:x-(x-width)/2] = img
最終草案:
import cv2
import numpy as np
if 1:
img = cv2.imread(in_img)
#get size
height, width, channels = img.shape
print (in_img,height, width, channels)
# Create a black image
x = height if height > width else width
y = height if height > width else width
square= np.zeros((x,y,3), np.uint8)
#
#This does the job
#
square[int((y-height)/2):int(y-(y-height)/2), int((x-width)/2):int(x-(x-width)/2)] = img
cv2.imwrite(out_img,square)
cv2.imshow("original", img)
cv2.imshow("black square", square)
cv2.waitKey(0)
您可以使用 numpy.vstack 垂直堆疊圖像,使用 numpy.hstack 水平堆疊圖像。
如果這解決了您的問題,請標記為已回答。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.