在读取像素值时,如何使用OpenCV和Python一致地读取和更改每个像素?

2024-03-28 08:20:13 发布

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

您好,谢谢您阅读我的问题!我注意到,当我在使用“(b,g,r)=image[c,r]”更改像素值之前尝试读取像素值时,python会跳过大部分像素吗?有什么原因吗?有什么解决办法吗?我正在努力的是试图增强图像中的任何红色,但如果python跳过像素就行不通了。。。你知道吗

import argparse
import cv2
import numpy as np

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
           help="Path to the image")
args = vars(ap.parse_args())

image = cv2.imread(args["image"])

for r in range(image.shape[1]):
    for c in range(image.shape[0]):
        count = count + 1

    #without this line the code works fine but when it is included it 
    #skips most of the pixels...
    (b,g,r) = image[c,r]

    canvas[c, r] = (255, 255, 255)

    cv2.imshow("changed canvas", canvas)
    cv2.waitKey(0)

Tags: theinimageimportforcountargparseargs
1条回答
网友
1楼 · 发布于 2024-03-28 08:20:13

正确的用法是使用numpy的ndarray函数item和itemset

要读取像素(0,0)处的红色值:

#note instead of rgb opencv writes the order as bgr so red is last
image.item(0,0,2)

设置:

image.itemset((0,0,2), 250)

相关问题 更多 >