我正在嘗試將影像分成兩部分并將兩個影像合并回來。我嘗試使用 NumPy 從影像上的每個點減去一個隨機值并存盤該值以使其成為新影像。然后我收到“照片無法打開此檔案,因為格式當前不受支持,或者檔案已損壞”。在第二張圖片上。那么如何使用這些值創建影像?
import numpy
import random
from PIL import Image
a = Image.new('RGB', [1280, 720], (255, 255, 255))
a = numpy.array(a)
value = []
for x in a:
for y in range(0, len(x)):
temp = [random.randrange(0, 255), random.randrange(
0, 255), random.randrange(0, 255)]
b = numpy.array(temp)
x[y] = x[y]-b
value.append(temp)
a = Image.fromarray(a)
a.show()
#print(value)
#print(len(value)) # 1280*720=921600
c = numpy.array(value)
d = Image.fromarray(c)
d.show()
uj5u.com熱心網友回復:
b = a.copy()
for position, color_value in numpy.ndenumerate(a):
b[position] = abs(color_value - random.randrange(0, 255))
d = Image.fromarray(b)
d.show()
uj5u.com熱心網友回復:
使用 Python 處理影像時,您應該嘗試使用向量化的 Numpy 操作,因為它們速度更快,而且更不容易出錯。如果您開始使用 Pythonlists和for回圈,恕我直言,您可能已經出錯了。
我不確定,但我認為您想生成一個隨機影像并從輸入影像中減去它,因此您需要兩個部分來重新創建整體,所以我認為您需要更像這樣的代碼:
import numpy as np
from PIL import Image
# Open paddington and ensure he is 3-channel RGB rather than palette
im = Image.open('paddington.png').convert('RGB')
# Make Numpy array from him
na = np.array(im)
# Make another Numpy array (i.e. image) same size as Paddington and full of random numbers
rand = np.random.randint(0,256, na.shape, dtype=np.uint8)
# See how that looks
Image.fromarray(rand).show()
# Subtract random image from Paddington - this vectorised Numpy, fast and easy to get right
split = na - rand
# See how that looks
Image.fromarray(split).show()
# Recreate original by adding random image back to split - vectorised Numpy again
joined = split rand
# See how that looks
Image.fromarray(joined).show()


如果您更喜歡堅持使用串列和for回圈,那么您的代碼中存在一些問題:
你一直在回收
a,所以最初它是PILImage,然后是 Numpyarray,然后是PILImage所以很難參考你之前計算的任何東西而不是
c = numpy.array(value)它給你一個陣列np.int64,你應該使用它c = numpy.array(value, dtype=np.uint8)來獲得一個無符號的 8 位陣列,因為PIL不會喜歡 192 位/像素您從串列中創建的 Numpy 陣列的形狀將是錯誤的,需要使用
d = Image.fromarray(c.reshape(720,1280,3))與其
random.randrange()為每個像素呼叫3 次并將結果轉換為 Numpy 陣列,您可以呼叫一次呼叫np.random.randint(0,256,(3),dtype=np.uint8)以將所有三個值作為 Numpy 陣列獲取您可能會遇到上溢和下溢的問題,因為您丟失了串列中值的基礎型別
uj5u.com熱心網友回復:
我想到了。我嘗試創建一個相同大小的新白色影像并回圈遍歷它以添加值。
import numpy
import random
from PIL import Image
a = Image.open('test.jpg')
a = numpy.array(a)
value = []
for x in a:
for y in range(0, len(x)):
temp = [random.randrange(0,255),random.randrange(0,255),random.randrange(0,255)]
b = numpy.array(temp)
x[y] = x[y]-b
value.append(temp)
a = Image.fromarray(a)
b=Image.new('RGB',a.size,(255,255,255))
b=numpy.array(b)
counter=0
for x in b:
for y in range(0,len(x)):
x[y]=tuple(value[counter])
counter =1
b=Image.fromarray(b)
a=numpy.array(a)
b=numpy.array(b)
a=numpy.add(a,b)
a=Image.fromarray(a)
a.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/344679.html
上一篇:將Java中的OpenCVMat轉換為Scala中的NumPy陣列
下一篇:如何列出numpy陣列中的最低值
