2015-03-18 43 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