Home > Software design >  Trying to put multiple images black and white, Python
Trying to put multiple images black and white, Python

Time:12-27

Im trying to put multiple images in black and white, but all the images are getting full black, i cant figure out where is the error:

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)

CodePudding user response:

I believe your problem is that j is not a single pixel, but a row of pixels. So each item added to lst will be a the weighted average of the first three pixels.

Instead, you could iterate through the rows.

lst = []
for x in img_data:
    for y in x:
        lst.append(y[0] * 0.2125   y[1] * 0.7169   y[2] * 0.0689)

Or you could also simplify the whole thing to a list comprehension.

lst = [y[0] * 0.2125   y[1] * 0.7169   y[2] * 0.0689 for y in x for x in img_data]
  • Related