0

コード全体(および使用された画像)は100%再現可能です。 enter image description hereオーバーレイされた輪郭が画像+輪郭回転後に整列していません.warpAffine with OpenCV

ここにコード内の手順を示します。

  1. 画像に輪郭([[386, 330], [398, 320], [382, 300], [370, 310], [386, 330]])をスーパーインポーズします。それはうまくいく。

  2. はシータ(= 90)で画像を回転warpAffine

  3. を用いて正確に同じサイズ、同じ回転機能のダミー画像における輪郭の点のそれぞれを回転させます。

  4. 回転したポイントの座標を検索します。

  5. 回転した画像に回転した点をスーパーインポーズします。

私がラインナップにそれらを期待したが、彼らはありませんを行う

何故その理由が考えられますか?

#! /usr/bin/env python                        
import numpy as np 
import cv2 
from shapely.geometry.polygon import LinearRing 

theta = 90 
image_path = 'image.tiff' 
orig_image = cv2.imread(image_path) 

wnd_str = 'unrotated' 
cv2.namedWindow(wnd_str,cv2.WINDOW_NORMAL) 
cv2.moveWindow(wnd_str, 0, 0) 

rows,cols, channels = orig_image.shape 
print 'Loaded image shape {}'.format(orig_image.shape) 

blank_image = np.zeros((rows, cols, 3), np.uint8) 
print 'Blank image shape {}'.format(blank_image.shape) 

M = cv2.getRotationMatrix2D((rows/2, cols/2), theta, 1.0) 
rot_image = cv2.warpAffine(orig_image, M, (rows, cols), flags=cv2.INTER_CUBIC+cv2.BORDER_CONSTANT) 
print 'Rotated image shape {}'.format(rot_image.shape) 

white = (255, 255, 255) 

#contours overlayed on unrotated image                    
pts = [[386, 330], [398, 320], [382, 300], [370, 310], [386, 330]] 
poly_pts = [] 
for p in pts: poly_pts.append(p) 
poly_pts = np.array(poly_pts[0:-1], np.int32) 
poly_pts = poly_pts.reshape((-1,1,2)) 

cv2.polylines(orig_image, [poly_pts], True, white, 1) 
cv2.imshow(wnd_str, orig_image) 
cv2.waitKey(0) 

#generate contours for the rotated image                   
rot_poly_pts = [] 
for p in pts: 
    x, y = p 

    blank_image = np.zeros((rows, cols, 3), np.uint8) 

    blank_image[x,y] = (255, 255, 255) 
    blank_image_affine = cv2.warpAffine(blank_image, M, (rows, cols), flags=cv2.INTER_CUBIC+cv2.BORDER_CONSTANT) 

    rotated_y, rotated_x, rotated_z = np.unravel_index(blank_image_affine.argmax(), blank_image_affine.shape) 

    rot_poly_pts.append([rotated_x, rotated_y]) 

rot_poly_pts = np.array(rot_poly_pts[0:-1], np.int32) 
rot_poly_pts = rot_poly_pts.reshape((-1,1,2)) 
cv2.polylines(rot_image, [rot_poly_pts], True, white, 1) 

wnd_str = 'rotated {}'.format(theta) 
cv2.namedWindow(wnd_str,cv2.WINDOW_NORMAL) 
cv2.moveWindow(wnd_str, 0, 0) 
cv2.imshow(wnd_str, rot_image) 

cv2.waitKey(0) 
cv2.destroyAllWindows() 


    [1]: https://i.stack.imgur.com/pyxmq.png 

ここここで、回転後の画像と重畳だ整列輪郭 enter image description here

と原画像です。 enter image description here

答えて

1

wrapAffineは、いずれかの側にクリップされたピクセルで画像を生成します。この手順の有効な代替案は、転置してから反転することです。

dst = cv2.flip(img.transpose(1,0,2),0) 

dst = destination image; 
img = source image; 

img.transpose(col,row,channel) = 1,0,2我々は唯一の行とCOLを転置し、そのままチャンネルを維持したいので、この順番に対応しています。

cv2.flip =転置操作中に発生したミラーリング効果に対抗する。ソース画像(横または縦)に応じて、フラグを0または1と変更します。