[英]Can I use cv2 or Numpy to Invert this picture?
我可以使用 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)
不確定您遇到了什么錯誤。 也許這里的東西會有所幫助?
語法: cv2.cv.flip(src, flipCode[, dst] )
參數: src:輸入數組。 dst:與 src 大小和類型相同的輸出數組。 翻轉代碼:指定如何翻轉數組的標志; 0 表示繞 x 軸翻轉,正值(例如 1)表示繞 y 軸翻轉。 負值(例如,-1)表示圍繞兩個軸翻轉。
返回值:它返回一個圖像。 如在 OpenCV 中發現的
example code:
# Python program to explain cv2.flip() method
# importing cv2
import cv2
# path
path = r'C:\Users\user\Desktop\geeks14.png'
# Reading an image in default mode
src = cv2.imread(path)
# Window name in which image is displayed
window_name = 'Image'
# Using cv2.flip() method
# Use Flip code 0 to flip vertically
image = cv2.flip(src, 0)
# Displaying the image
cv2.imshow(window_name, image)
cv2.waitKey(0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.