简体   繁体   English

如何更改灰度图像中的特定像素值?

[英]How to change specific pixel value in grayscale image?

I want to change the pixel value of a grayscale image using OpenCV. 我想使用OpenCV更改灰度图像的像素值。

Assume that I have a grayscale image and I want to convert all its pixel to 0 value one at a time. 假设我有一个灰度图像,我希望一次将其所有像素转换为0值。 So that the resultant image is completely black. 这样得到的图像完全是黑色的。 I tried this but there is no change in the image: 我尝试了这个,但图像没有变化:

image = cv2.imread('test_image.png',0)

for i in range(image.shape[0]):
    for j in range(image.shape[1]):
        image[i, j] = 0

Result: 结果:

display the updated image 显示更新的图像

In most cases, you want to avoid using double for loops to modify pixel values since it is very slow. 在大多数情况下,您希望避免使用双for循环来修改像素值,因为它非常慢。 A better approach is to use Numpy for pixel modification since OpenCV uses Numpy arrays to display images. 更好的方法是使用Numpy进行像素修改,因为OpenCV使用Numpy数组来显示图像。 To achieve your desired result, you can use np.zeros to create a completely black image with the same shape as the original image. 要获得所需的结果,可以使用np.zeros创建一个与原始图像具有相同形状的完全黑色图像。

import cv2
import numpy as np

image = cv2.imread("test_image.png", 0)

black = np.zeros(image.shape, np.uint8)

cv2.imshow('image', image)
cv2.imshow('black', black)
cv2.waitKey(0)

For example with a test image. 例如,带有测试图像。 Original (left), result (right) 原件(左),结果(右)

I would suggest you to always try manipulating the copy of an image so that the image doesn't get affected in the wrong way. 我建议你总是尝试操作图像的副本,这样图像就不会以错误的方式受到影响。 Coming to your question, you can do the following: 提出您的问题,您可以执行以下操作:

import cv2

image = cv2.imread('test_image.png',0)

#Creating a copy of the image to confirm right operation is performed on the image.
image_copy = image.copy() 
image_copy[:,:] = [0] #Setting all values to 0.

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

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