我正在尝试创建一个滤镜,为所有图片创建棕褐色外观。但是我在过滤后的图像中发现了一些蓝色和青色的 Blob 。我认为它可能溢出了,但我试图解释这一点,但它并没有给我想要的影响。我不确定怎么了。原始链接位于https://www.dropbox.com/s/pd0esc8tef3smae/Lampard.jpg。修改后变为https://www.dropbox.com/s/f9n9lrhoi1qqs53/Lampard_blue.jpg
def filter3(path, cv2):
cv2.destroyAllWindows()
cv2.namedWindow("Filter 3")
img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
newImg = img
(i,j,k) = img.shape
for x in xrange(i):
for y in xrange(j):
b = img[x,y,0]
g = img[x,y,1]
r = img[x,y,2]
if(k == 4):
newImg[x,y,0] = np.uint16(b * 0.272 + g * 0.534 + r * 0.131)
newImg[x,y,1] = np.uint8(b * .349 + g * 0.686 + r * 0.168)
newImg[x,y,2] = np.uint8(b * 0.393 + g * 0.769 + r * 0.189)
# newB = np.uint16(b * 0.272 + g * 0.534 + r * 0.131)
# newG = np.uint16(b * .349 + g * 0.686 + r * 0.168)
# newR = np.uint16(b * 0.393 + g * 0.769 + r * 0.189)
# if(newB > 255):
# newImg[x,y,0] = np.uint8(255)
# else:
# newImg[x,y,0] = np.uint8(newB)
# if(newG > 255):
# newImg[x,y,1] = np.uint8(255)
# else:
# newImg[x,y,1] = np.uint8(newB)
# if(newR > 255):
# newImg[x,y,2] = np.uint8(255)
# else:
# newImg[x,y,2] = np.uint8(newB)
newImg[x,y,3] = img[x,y,3]
else:
newImg[x,y,0] = np.uint16(b * 0.272 + g * 0.534 + r * 0.131)
newImg[x,y,1] = np.uint8(b * .349 + g * 0.686 + r * 0.168)
newImg[x,y,2] = np.uint8(b * 0.393 + g * 0.769 + r * 0.189)
# if(newB > 255):
# newImg[x,y,0] = np.uint8(0)
# else:
# newImg[x,y,0] = np.uint8(newB)
cv2.imshow("Filter 3", newImg)
return newImg
在我看来,问题出在类型上。 Python 认为在操作后你想要整数。每个 channel 有 8 位。计算后你将获得值 256 (100000001) python 将只读取前 8 位 (00000001)。因此,您的形象有点奇怪。在我的例子中,这段代码有效:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('lena.jpg')
newImage = cv2.imread('lena.jpg')
i, j, k = img.shape
for x in xrange(i):
for y in xrange(j):
R = img[x,y,2] * 0.393 + img[x,y,1] * 0.769 + img[x,y,0] * 0.189
G = img[x,y,2] * 0.349 + img[x,y,1] * 0.686 + img[x,y,0] * 0.168
B = img[x,y,2] * 0.272 + img[x,y,1] * 0.534 + img[x,y,0] * 0.131
if R > 255:
newImage[x,y,2] = 255
else:
newImage[x,y,2] = R
if G > 255:
newImage[x,y,1] = 255
else:
newImage[x,y,1] = G
if B > 255:
newImage[x,y,0] = 255
else:
newImage[x,y,0] = B
cv2.imshow('image',newImage)
cv2.waitKey(0)
cv2.destroyAllWindows()
也许这不是很好的代码,但我对 Python 不熟悉。
我是一名优秀的程序员,十分优秀!