簡體   English   中英

為什么“matplotlib.pyplot.imshow”會返回帶有框架的形狀?

[英]Why “matplotlib.pyplot.imshow” returns shapes with a frame around them?

我的問題很簡單:為什么我在下面編寫的兩段代碼會給出兩個略有不同的輸出?

更具體地說,第一個使用 numpy.ndarray 形狀 (1000, 1000) 填充“1.0” np.float64 值,除了我想要有一個“正方形”的區域,它填充有“0.45” np.float64 值。 當我在軸上調用 plt.imshow 方法時,使用顏色圖“nipy_spectral”,它返回一個正方形,但周圍有一個奇怪的框架......

見下面的代碼和最后的左圖:

#Code1:
foreground = np.ones((1000, 1000))
foreground = foreground.astype(np.float64)

def drawSquare(centerYX : tuple = (0, 0), radius : int = 1):
    squareCoordinates = np.meshgrid([y for y in range(centerYX[0]-radius, centerYX[0]+radius+1, 1)],
                                    [x for x in range(centerYX[1]-radius, centerYX[1]+radius+1, 1)])
    return squareCoordinates

square1 = drawSquare((round(foreground.shape[0]/2), round(foreground.shape[1]/2)), 200)
foreground[square1[0], square1[1]] = 0.45

fig, ax = plt.subplots(1)
ax.imshow(foreground, cmap = "nipy_spectral", vmin = 0.0, vmax = 1.0, , interpolation = None)
plt.show();

在第二段代碼中,我使用了形狀為 (1000, 1000, 4) 的 numpy.ndarray,我填充了與“nipy_spectral”顏色圖(我的背景)的最后一種顏色相對應的 RGBA 序列,除了正方形區域,我用參數“0.45”調用“nipy_spectral”顏色圖獲得的 RGBA 序列填充。

在這種情況下,我已經有了一個不需要通過 Axes.imshow 方法的“cmap”參數進行任何轉換的 RGBA 圖像/數組。 在這種情況下,output 是預期的:一個沒有任何奇怪框架的正方形

見下面的代碼和最后的右圖:

#Code2:
foreground = np.zeros((1000, 1000, 4))
foreground[:, :] = [0.8, 0.8, 0.8, 1.0]
foreground = foreground.astype(np.float64)

def drawSquare(centerYX : tuple = (0, 0), radius : int = 1):
    squareCoordinates = np.meshgrid([y for y in range(centerYX[0]-radius, centerYX[0]+radius+1, 1)],
                                    [x for x in range(centerYX[1]-radius, centerYX[1]+radius+1, 1)])
    return squareCoordinates

square1 = drawSquare((round(foreground.shape[0]/2), round(foreground.shape[1]/2)), 200)

nipy_spectral_cm = matplotlib.cm.get_cmap("nipy_spectral")
foreground[square1[0], square1[1]] = nipy_spectral_cm(0.45)

fig, ax = plt.subplots(1)
ax.imshow(foreground)
plt.show();

在此處輸入圖像描述

為什么第一段代碼(Code1)給出了一個帶有奇怪框架的正方形?

該幀是由於插值。 它也出現在第二個代碼中(只需放大圖像,您就會看到它),但不太明顯,因為它的顏色更接近綠色方塊的顏色:

代碼 2 --> 內插為藍綠色:

foreground[299:301,299:301,0]
#array([[0.8, 0.8],
#       [0.8, 0. ]])

foreground[299:301,299:301,1]
#array([[0.8       , 0.8       ],
#       [0.8       , 0.60261373]])

foreground[299:301,299:301,2]
#array([[0.8, 0.8],
#       [0.8, 0. ]])

代碼 1 --> 內插為黃色:

foreground[299:301,299:301]
#array([[1.  , 1.  ],
#       [1.  , 0.45]])

使用interpolate='none'關閉插值並獲得清晰的切角。 您使用None而不是'none' None是默認值,並預設為'antialiased' ,有關詳細信息,請參見此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM