尝试将多张图片设为黑白,Python
Trying to put multiple images black and white, Python
我试图将多张图片设为黑白,但所有图片都变成了全黑,我不知道哪里出错了:
def bw():
#images = [cv2.imread(file) for file in glob.glob("C:/PythonProjects/*frame.jpg")]
img_dir = "C:/PythonProjects" # Directory of all images
data_path = os.path.join(img_dir, '*frame.jpg') #Filter becouse I only want some type of images
files = glob.glob(data_path)
data = []
plus = Image.open("124frame.jpg") #getting the image just to get his size for the FOR cycle
for j in files:
img = cv2.imread(j)
data.append(img) #Save the images into a list
for i in range(0, 130): #128 are the numbers of images I want to work with
img_data = data[i] #Select image by image from the list
# Run the image
lst = []
for j in img_data:
lst.append(j[0] * 0.2125 + j[1] * 0.7169 + j[2] * 0.0689) #Black and White algorithm
#Using the pixels then saving them to a List
#New Image
new_image = Image.new("L", plus.size)
new_image.putdata(lst) #Put the data from the list to the new image
new_image = numpy.array(new_image)
#Save the image
cv2.imwrite("bwframe%d.jpg" % i, new_image)
我相信你的问题是 j
不是一个像素,而是一排像素。因此,添加到 lst
的每个项目都将是前三个像素的加权平均值。
相反,您可以遍历行。
lst = []
for x in img_data:
for y in x:
lst.append(y[0] * 0.2125 + y[1] * 0.7169 + y[2] * 0.0689)
或者您也可以将整个事情简化为列表理解。
lst = [y[0] * 0.2125 + y[1] * 0.7169 + y[2] * 0.0689 for y in x for x in img_data]
我试图将多张图片设为黑白,但所有图片都变成了全黑,我不知道哪里出错了:
def bw():
#images = [cv2.imread(file) for file in glob.glob("C:/PythonProjects/*frame.jpg")]
img_dir = "C:/PythonProjects" # Directory of all images
data_path = os.path.join(img_dir, '*frame.jpg') #Filter becouse I only want some type of images
files = glob.glob(data_path)
data = []
plus = Image.open("124frame.jpg") #getting the image just to get his size for the FOR cycle
for j in files:
img = cv2.imread(j)
data.append(img) #Save the images into a list
for i in range(0, 130): #128 are the numbers of images I want to work with
img_data = data[i] #Select image by image from the list
# Run the image
lst = []
for j in img_data:
lst.append(j[0] * 0.2125 + j[1] * 0.7169 + j[2] * 0.0689) #Black and White algorithm
#Using the pixels then saving them to a List
#New Image
new_image = Image.new("L", plus.size)
new_image.putdata(lst) #Put the data from the list to the new image
new_image = numpy.array(new_image)
#Save the image
cv2.imwrite("bwframe%d.jpg" % i, new_image)
我相信你的问题是 j
不是一个像素,而是一排像素。因此,添加到 lst
的每个项目都将是前三个像素的加权平均值。
相反,您可以遍历行。
lst = []
for x in img_data:
for y in x:
lst.append(y[0] * 0.2125 + y[1] * 0.7169 + y[2] * 0.0689)
或者您也可以将整个事情简化为列表理解。
lst = [y[0] * 0.2125 + y[1] * 0.7169 + y[2] * 0.0689 for y in x for x in img_data]