Python Opencv - 无法更改图片的像素值

标签 python opencv pixel

需要将下图的白色像素改成黑色,黑色像素改成白色 enter image description here

    import cv2

    img=cv2.imread("cvlogo.png")

带有白色背景的基本 opencv Logo 并将图片调整为固定的已知大小

    img=cv2.resize(img, (300,300))#(width,height)


    row,col=0,0
    i=0

现在用for循环检查每个像素的行和列位置

如果像素是白色,则将其更改为黑色,或者如果像素是黑色,则将其更改为白色。

    for row in range(0,300,1):
        print(row)
        for col in range(0,300,1):
            print(col)
            if img[row,col] is [255,255,255] : #I have used == instead of 'is'..but there is no change 
                img[row,col]=[0,0,0]
            elif img[row,col] is [0,0,0]:
                img[row,col]=[255,255,255]

执行没有错误,但没有将像素值分别更改为黑色或白色。更多 if 语句也没有执行..太多的困惑..

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

最佳答案

我不是很有经验,但我会使用比循环更快的 numpy.where() 来完成。

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Read the image
original_image=cv2.imread("cvlogo.png")
# Not necessary. Make a copy to plot later
img=np.copy(original_image)

#Isolate the areas where the color is black(every channel=0) and white (every channel=255)
black=np.where((img[:,:,0]==0) & (img[:,:,1]==0) & (img[:,:,2]==0))
white=np.where((img[:,:,0]==255) & (img[:,:,1]==255) & (img[:,:,2]==255))

#Turn black pixels to white and vice versa
img[black]=(255,255,255)
img[white]=(0,0,0)

# Plot the images
fig=plt.figure()
ax1 = fig.add_subplot(1,2,1)
ax1.imshow(original_image)
ax1.set_title('Original Image')
ax2 = fig.add_subplot(1,2,2)
ax2.imshow(img)
ax2.set_title('Modified Image')
plt.show()

enter image description here

关于Python Opencv - 无法更改图片的像素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45613544/

相关文章:

python - 如何比较 pandas groupby 对象的列值并将它们汇总到新的列行中

python - 在 Python 中使用 beautifulsoup 从网站中提取数字

c++ - OpenCV C++ 接口(interface)如何管理 ROI

image - OpenCV 可以读取的最大图像是多少?

arrays - 从像素阵列问题中获取 NSImage (Swift)

jQuery UI 只能向左拖动

python - 计算元组列表中元素的可达性

python - 如何使用 range() 在 Python 中迭代大数?

android - AsyncTask Android

ios - 照片编辑应用 iOS