繁体   English   中英

Python中的OpenCV-操纵像素

[英]OpenCV in Python - Manipulating pixels

我正在使用python 2.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设置图像的像素-但是result.bmp是原始图像的精确副本。

我究竟做错了什么?

编辑:

我知道遍历像素是个坏主意,但是我的代码的无效部分是什么?

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

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

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

对于“全白”:

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

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

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

我想您的图像确实发生了变化,但是它仅在第一行上,如果您没有放大,则可能看不到。如果您像这样更改代码,它就可以工作:

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

请注意,如上所述,我也不建议逐像素迭代图像。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM