2015-03-18 126 views
1

我使用python 2.7和OpenCV將圖像設置爲全部白色像素,但它不起作用。Python中的OpenCV - 操縱像素

這裏是我的代碼:

import cv2 
import numpy as np 

image = cv2.imread("strawberry.jpg") #Load image 

imageWidth = image.shape[1] #Get image width 
imageHeight = image.shape[0] #Get image height 

xPos = 0 
yPos = 0 

while xPos < imageWidth: #Loop through rows 
    while yPos < imageHeight: #Loop through collumns 

     image.itemset((xPos, yPos, 0), 255) #Set B to 255 
     image.itemset((xPos, yPos, 1), 255) #Set G to 255 
     image.itemset((xPos, yPos, 2), 255) #Set R to 255 

     yPos = yPos + 1 #Increment Y position by 1 
    xPos = xPos + 1 #Increment X position by 1 

cv2.imwrite("result.bmp", image) #Write image to file 

print "Done" 

我使用numpy的設置圖像的像素 - 但result.bmp是原始圖像的精確副本。

我在做什麼錯?

編輯:

我知道這是一個壞主意來遍歷像素,但什麼是我的代碼的非功能部分?

回答

1

除開@berak提出的有效建議,如果這是你寫的代碼來學習你想要使用的庫,那麼你犯了兩個錯誤:

  1. 你忘了重置yPos內部循環後的行索引計數器
  2. 您將xPos, yPos的順序切換爲itemset。 。

我猜你的形象的確發生了變化,但它僅是第一行,你可能看不到,如果你不放大。如果你改變你這樣的代碼,它的工作原理:

import cv2 
import numpy as np 

image = cv2.imread("testimage.jpg") #Load image 

imageWidth = image.shape[1] #Get image width 
imageHeight = image.shape[0] #Get image height 

xPos, yPos = 0, 0 

while xPos < imageWidth: #Loop through rows 
    while yPos < imageHeight: #Loop through collumns 

     image.itemset((yPos, xPos, 0), 255) #Set B to 255 
     image.itemset((yPos, xPos, 1), 255) #Set G to 255 
     image.itemset((yPos, xPos, 2), 255) #Set R to 255 

     yPos = yPos + 1 #Increment Y position by 1 

    yPos = 0 
    xPos = xPos + 1 #Increment X position by 1 

cv2.imwrite("result.bmp", image) #Write image to file 

請注意,我也不建議像前面提到的那樣逐個像素地迭代圖像。

1

規則一與opencv/python:從來沒有遍歷像素,如果你可以避免它!

,如果你想所有的像素設置爲(1,2,3),它是那麼容易,因爲:

image[::] = (1,2,3) 

爲 '全白':

image[::] = (255,255,255) 
+0

謝謝,但什麼不在我的代碼中工作,我只是將這個例子應用到我正在處理的另一個項目中。對不起,如果我應該更清楚。 – 2015-03-18 22:17:29