iT邦幫忙

0

使用Python設計漸層的灰階影像

影像大小:512x100,灰階自左到右分別為0~255,並儲存影像檔案。
我的程式:
import numpy as np
import cv2

img = np.zeros([100,512],dtype="uint8")

for i in range(0,256):
img[:,:] += i

cv2.imshow("Example",img)
cv2.imwrite("color.bmp",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

結果:
https://ithelp.ithome.com.tw/upload/images/20200226/20119130GvY8g6Pn52.png
請問需要怎麼修改才會正確?

你把 img Print 出來應該就知道了
你用 [:,:] 每次改的不都一樣嗎
dragonH iT邦超人 5 級 ‧ 2020-02-26 11:28:47 檢舉
改你的這邊

```
for i in range(0,256):
img[:,:] += i
```
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
froce
iT邦大師 1 級 ‧ 2020-02-26 16:01:20
import numpy as np
import cv2

row = np.array([(i/2, i/2, i/2) for i in range(512)], dtype="uint8")
img = np.repeat(np.array([row], dtype="uint8"), 100, axis=0)

cv2.imwrite('color_img.jpg', img)
cv2.imshow("image", img)
cv2.waitKey()

大概就這樣吧,不知道幹嘛要寫迴圈。
另外看你的code害我搞不清楚圖片的表示方式...
時間都花在查基礎知識上。

jorsonlee iT邦新手 4 級 ‧ 2022-03-06 13:42:18 檢舉

想要請問一下
row的定義部分np.array([(i/2, i/2, i/2)...這邊用3個為一組這樣是為什麼呢?
因為我用一組直接跑出來結果好像一樣

froce iT邦大師 1 級 ‧ 2022-03-07 09:04:22 檢舉

2年前的回答了...

cv2吃的是BGR,三個一組代表一個 pixel 裡面的BGR混色,因為題目要的是512 pixel 所以用 i/2的範圍才會是0~255。
後面repeat 100才能得到一個 512*100 的灰階漸變圖片

我要發表回答

立即登入回答