2017-08-12 54 views
2

我有各種各樣的長方形形象。我需要修改它們以統一方形(不同大小)。如何使用OpenCV和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) 

如何將它們堆疊在彼此所以原始圖像的頂部被垂直和水平中心的黑色形狀的頂部?

+0

[調整圖像畫布以保持Python,OpenCv中的方形寬高比的可能的副本](https://stackoverflow.com/questions/44720580/resize-image-canvas-to-maintain-square-aspect-ratio-in -python-OpenCV的) –

回答

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[(y-height)/2:y-(y-height)/2, (x-width)/2:x-(x-width)/2] = img 
     cv2.imwrite(out_img,square) 
     cv2.imshow("original", img) 
     cv2.imshow("black square", square) 
     cv2.waitKey(0) 
0

您可以使用numpy.vstack垂直堆疊圖像和numpy.hstack到水平疊加圖像。

如果您解決了您的問題,請標記爲已解答。

相關問題