[英]What's the fastest way to remap pixel values in OpenCV in Python?
[英]What is wrong with my OpenCV remap()ing?
我從OpenCV中的Image轉換中獲取了答案https://stackoverflow.com/a/10374811/4828720 ,並嘗試將其調整為我的圖像。
在其中,我確定了方格磚中心的像素坐標,如下圖所示:
我的目標分辨率是784.我計算了像素的目標坐標。 我得到的代碼是這樣的:
import cv2
from scipy.interpolate import griddata
import numpy as np
source = np.array([
[315, 15],
[962, 18],
[526, 213],
[754, 215],
[516, 434],
[761, 433],
[225, 701],
[1036, 694],
], dtype=int)
destination = np.array([
[14, 14],
[770, 14],
[238, 238],
[546, 238],
[238, 546],
[546, 546],
[14, 770],
[770, 770]
], dtype=int)
source_image = cv2.imread('frames.png')
grid_x, grid_y = np.mgrid[0:783:784j, 0:783:784j]
grid_z = griddata(destination, source, (grid_x, grid_y), method='cubic')
map_x = np.append([], [ar[:,1] for ar in grid_z]).reshape(784,784)
map_y = np.append([], [ar[:,0] for ar in grid_z]).reshape(784,784)
map_x_32 = map_x.astype('float32')
map_y_32 = map_y.astype('float32')
warped_image = cv2.remap(source_image, map_x_32, map_y_32, cv2.INTER_CUBIC)
cv2.imwrite("/tmp/warped2.png", warped_image)
如果我運行它,沒有任何源點最終到達預定的目的地,但我得到一個扭曲的混亂。 我在這里添加了目的地點:
我哪里錯了? 我注意到我的網格和地圖數組的分布不如示例中那樣好。 點數太少了嗎? 我是否需要在常規網格中使用它們? 我只嘗試使用外角的四個點而沒有運氣。
如果您只有8個點用於扭曲圖像中沒有真正的失真,我建議使用此處所述的透視變換。
您引用的鏈接會嘗試消除導致非直線的其他扭曲,但圖像中的所有線條都是直線。
代碼看起來像:
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('image.png')
rows,cols,ch = img.shape
pts1 = np.float32([
[315, 15],
[962, 18],
[225, 701],
[1036, 694],
], dtype=int)
pts2 = np.float32([
[14, 14],
[770, 14],
[14, 770],
[770, 770]
], dtype=int)
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(784,784))
plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()
整個問題是我再次被numpy的行/列索引而不是x / y弄糊塗了。 #opencv IRC頻道中有人指出了這一點。 我的源和目標數組必須切換其列:
source = np.array([
[15, 315],
[18, 962],
[213, 526],
[215, 754],
[434, 516],
[433, 761],
[701, 225],
[694, 1036],
], dtype=int)
destination = np.array([
[14, 14],
[14, 770],
[238, 238],
[238, 546],
[546, 238],
[546, 546],
[770, 14],
[770, 770]
], dtype=int)
然后它按預期工作(忽略丑陋的扭曲,這是一個簡化的坐標列表來找到bug):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.