【发布时间】:2021-07-29 20:44:49
【问题描述】:
我可以使用 cv2 或 numpy 将图像变成负片吗?如下所示,但我仍需要编辑。
我的问题主要是代码的顶部,如果我可以使用它来将灰度和黑白都反转为负数?
import cv2
import numpy as np
img = cv2.imageread('imagename.jpg')
print(img.dtype)
image_neg = 255 - img
cv2.imshow('negative',image_neg)
cv2.waitKey(0)
#######################################
from images import Image
def invert(image):
def blackAndWhite(image):
blackPixel = (0, 0, 0)
whitePixel = (255, 255, 255)
for y in range(image.getHeight()):
for x in range(image.getWidth()):
(r, g, b) = image.getPixel(x, y)
average = (r + g + b) // 3
if average < 128:
image.setPixel(x, y, blackPixel)
else:
image.setPixel(x, y, whitePixel)
def grayscale(image):
for y in range(image.getHeight()):
for x in range(image.getWidth()):
(r, g, b) = image.getPixel(x, y)
r = int(r * 0.299)
g = int(g * 0.587)
b = int(b * 0.114)
lum = r + g + b
image.setPixel(x, y, (lum, lum, lum))
def main():
filename = input("Enter the image file name: ")
image = Image(filename)
#Invert image
invert(image)
image.draw()
#Covert to greyscale, then invert
"""grayscale(image)
invert(image)
image.draw()"""
#Convert to black and white, then invert
"""blackAndWhite(image)
invert(image)
image.draw()"""
if __name__ == "__main__":
main()
我收到以下错误:
Traceback (most recent call last):
File "invert.py", line 14, in <module>
image_neg = 255 - image
NameError: name 'image' is not defined
我把开头的代码改成这样说:
import cv2
import numpy as np
image = cv2.imageread('smokey.gif')
print(image.dtype)
image_neg = 255 - image
cv2.imshow('negative',image_neg)
cv2.waitKey(0)
我认为这可行,但它告诉我行 - “invertedImage = cv2.bitwise_not(imageToInvert)”有一个 SyntaxError: invalid non-printable character U+00A0
我在这里正确编辑了我的代码(4 个空格),但我不知道为什么它仍然不能正确显示。
from images import Image
import cv2
def invert(image):
imageToInvert = cv2.imread(filepath)
invertedImage = cv2.bitwise_not(imageToInvert)
cv2.imgwrite("BWimage.png",invertedImage)
print("inverted image saved")
File_path='smokey.gif'
invert(File_path)
【问题讨论】:
-
帖子下方有一个灰色的编辑按钮。该按钮看起来像一个标签,但您可以按下它并编辑您的代码。我不明白为什么
image_neg = 255 - img不够好。编辑时请添加python标签、opencv标签和image-processing标签。 -
谢谢@Rotem 我已经添加了标签。我很惊讶它不能正常工作。
-
将
img = cv2.imageread('imagename.jpg')替换为img = cv2.imread('imagename.jpg')。什么不工作?第一部分?第二部分?编辑问题? -
请解释为什么你说它不起作用。你得到什么输出?
image_neg = 255 - img确实适用于 8 位无符号图像。 -
我更改了代码但仍然无法正常工作。
标签: python image opencv image-processing