Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 增加彩色图像亮度时索引数不正确_Python_Python 3.x_Opencv - Fatal编程技术网

Python 增加彩色图像亮度时索引数不正确

Python 增加彩色图像亮度时索引数不正确,python,python-3.x,opencv,Python,Python 3.x,Opencv,代码在读取灰度图像以执行亮度时工作正常。但同样的代码不适用于彩色图像。 如何从彩色图像执行亮度操作 在参数0处使用cv2.imread读取图像时效果很好,但我尝试使用1,但效果不好,因为0用于灰度图像,1用于彩色图像 import numpy as np import cv2 img = cv2.imread('image1.jpg',1) height = img.shape[0] width = img.shape[1] brightness = 100 for i in np.ara

代码在读取灰度图像以执行亮度时工作正常。但同样的代码不适用于彩色图像。 如何从彩色图像执行亮度操作

在参数0处使用cv2.imread读取图像时效果很好,但我尝试使用1,但效果不好,因为0用于灰度图像,1用于彩色图像

import numpy as np
import cv2

img = cv2.imread('image1.jpg',1)

height = img.shape[0]
width = img.shape[1]
brightness = 100

for i in np.arange(height):
    for j in np.arange(width):
        a = img.item(i,j)
        b = a + brightness
        if b > 255:
            b = 255
        img.itemset((i,j), b)

cv2.imwrite('brightness.jpg', img)

cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

我希望读取彩色图像并执行亮度操作,但它显示的值错误:数组的索引数不正确

问题是彩色图像有多个不同颜色的通道(例如,RGB或RGBA),因此当您执行
img.item(I,j)
时,您缺少第三维(三个颜色通道). 您可以添加另一个在每个颜色通道上循环的for循环,但也可以只使用numpy的
minimum
函数来提高效率(即,将255添加到图像的值中,如果大于255,则将使用255)


一种解决方案是使用OpenCV normalize将图像拉伸到完整的动态范围(0到255)

以下是两个输出结果,具体取决于最小和最大拉伸限制。请注意,normalize处理浮点数据,最小值和最大值名义上被拉伸到0到1的全范围。但是,如果最小值和最大值超出0到1的范围,我们需要将结果剪裁到该范围,然后将其缩放到0到255的范围,然后保存为uint8进行输出

The first result is stretched to min and max of 0 to 1.

The second result is stretched to min and max of 0 to 1.2 in order to make it even brighter.

图片:


最小值和最大值(0到1):

最小值和最大值(0到1.2):

看一看
The first result is stretched to min and max of 0 to 1.

The second result is stretched to min and max of 0 to 1.2 in order to make it even brighter.
#!/bin/python3.7

import cv2
import numpy as np

# read image
img = cv2.imread("zelda1_bm20_cm20.jpg", cv2.IMREAD_COLOR)

# normalize float versions
norm_img1 = cv2.normalize(img, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
norm_img2 = cv2.normalize(img, None, alpha=0, beta=1.2, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

# scale to uint8
norm_img1 = (255*norm_img1).astype(np.uint8)
norm_img2 = np.clip(norm_img2, 0, 1)
norm_img2 = (255*norm_img2).astype(np.uint8)

# write normalized output images
cv2.imwrite("zelda1_bm20_cm20_normalize1.jpg",norm_img1)
cv2.imwrite("zelda1_bm20_cm20_normalize2.jpg",norm_img2)

# display input and both output images
cv2.imshow('original',img)
cv2.imshow('normalized1',norm_img1)
cv2.imshow('normalized2',norm_img2)
cv2.waitKey(0)
cv2.destroyAllWindows()