gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:57:59 25 4
gpt4 key购买 nike

需要将下图的白色像素改成黑色,黑色像素改成白色 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com