Python中的OpenCV操作像素

2024-09-28 21:25:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python2.7和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设置图像的像素-但是结果.bmp是原始图像的完全复制品。在

我做错什么了?在

编辑:

我知道迭代像素不是个好主意,但是我的代码中不起作用的部分是什么?在


Tags: to代码图像imageimportnumpyget像素
2条回答

除了@berak提出的有效建议外,如果这是您为了学习要使用的库而编写的代码,那么您犯了两个错误:

  1. 您忘记在内部while循环之后重置yPos行索引计数器
  2. 您在itemset中切换了xPos, yPos的顺序。在

我想你的图像确实改变了,但它只在第一行,如果你不放大,你可能看不到。如果像这样更改代码,它会起作用:

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

注意,我也不建议像前面提到的那样逐个像素地迭代图像。在

opencv/python的第一条规则:如果可以避免的话,永远不要迭代像素!在

如果您想将所有像素设置为(1,2,3),那么很简单:

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

对于“全白”:

^{pr2}$

相关问题 更多 >