找到所有超过50%黑色的图像 – Python

huangapple go评论53阅读模式
英文:

Find all images that are over 50% black - Python

问题

from PIL import Image
import glob

images = glob.glob('/content/drive/MyDrive/cropped_images/*.png') # 寻找所有匹配指定模式的文件名

for image in images:
    with open(image, 'rb') as file:
        img = Image.open(file)
        pixels = list(img.getdata())            # 获取像素数据,以扁平序列表示
        black_thresh = (50, 50, 50)
        nblack = 0
        for pixel in pixels:
            if pixel < black_thresh:
                nblack += 1
            n = len(pixels)

        if (nblack / float(n)) > 0.5:
            print(file)
英文:

I am trying to write code that will iterate over a directory of images and tell me which images are over 50% black - so I can get rid of those. This is what I have, but it isn't returning any results:

from PIL import Image
import glob


images = glob.glob(&#39;/content/drive/MyDrive/cropped_images/*.png&#39;) #find all filenames specified by pattern

for image in images:
    with open(image, &#39;rb&#39;) as file:
        img = Image.open(file)
        pixels = list(img.getdata())            # get the pixels as a flattened sequence
        black_thresh = (50,50,50)
        nblack = 0
        for pixel in pixels:
            if pixel &lt; black_thresh:
                nblack += 1
            n = len(pixels)

        if (nblack / float(n)) &gt; 0.5:
          print(file)

答案1

得分: 0

Hannah,在Python中,元组比较可能不是你所期望的:https://stackoverflow.com/questions/5292303/how-does-tuple-comparison-work-in-python 。它是逐个元素比较的,只用于决定胜负。也许你对超过50%黑色的定义与你的代码不符?

我在一幅暗色图片上运行了上述代码,我的文件正常打印。示例PNG图片:https://www.nasa.gov/mission_pages/chandra/news/black-hole-image-makes-history 。

建议:将超过50%黑色的定义转化为可编写的代码,将循环中的n值提取出来,当文件满足条件时,将其添加到一个列表中。

英文:

Hannah, tuple comparison in python might not be what you expect: https://stackoverflow.com/questions/5292303/how-does-tuple-comparison-work-in-python . It is element by element, only for tiebreaking. Perhaps your definition of over 50% black is not what you have mapped to code?

I ran the above code on a dark image and my file printed just fine. Example png: https://www.nasa.gov/mission_pages/chandra/news/black-hole-image-makes-history .

Recommendations: define over 50% black to something you can put in code, pull the n out of the for loop, add files to a list when they satisfy your criteria.

huangapple
  • 本文由 发表于 2023年2月10日 06:42:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75405207.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定