简体   繁体   English

Python中的OpenCV-操纵像素

[英]OpenCV in Python - Manipulating pixels

I am using python 2.7 and OpenCV to set an image to all white pixels, but it is not working. 我正在使用python 2.7和OpenCV将图像设置为所有白色像素,但无法正常工作。

Here is my code: 这是我的代码:

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"

I use numpy to set the pixels of the image - but the result.bmp is an exact copy of the original image. 我使用numpy设置图像的像素-但是result.bmp是原始图像的精确副本。

What am I doing wrong? 我究竟做错了什么?

EDIT: 编辑:

I know it is a bad idea to iterate over pixels, but what is the non functioning part of my code? 我知道遍历像素是个坏主意,但是我的代码的无效部分是什么?

rule one with opencv/python: never iterate over pixels, if you can avoid it ! 使用opencv / python的规则之一:如果可以避免的话, 永远不要迭代像素!

if you wanted to set all of the pixels to (1,2,3), it's as easy as: 如果您想将所有像素设置为(1,2,3),则很简单:

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

for 'all white': 对于“全白”:

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

Aside from the valid suggestion made by @berak, if this is code that you wrote to get to learn the library you want to use, then you've made 2 mistakes: 除了@berak提出的有效建议之外,如果这是您为了学习要使用的库而编写的代码,那么您犯了2个错误:

  1. You forgot to reset the yPos row index counter after the inner while loop 您忘了在内部while循环之后重置yPos行索引计数器
  2. You switched the order of xPos, yPos in itemset . 您切换顺序xPos, yPositemset

I guess that your image did change, but it's only on the first row, which you might not see if you don't zoom in. If you change your code like this, it works: 我想您的图像确实发生了变化,但是它仅在第一行上,如果您没有放大,则可能看不到。如果您像这样更改代码,它就可以工作:

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

Note that I would also not recommend iterating over an image pixel by pixel, as mentioned before. 请注意,如上所述,我也不建议逐像素迭代图像。

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

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