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

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

Find all images that are over 50% black - Python

问题

  1. from PIL import Image
  2. import glob
  3. images = glob.glob('/content/drive/MyDrive/cropped_images/*.png') # 寻找所有匹配指定模式的文件名
  4. for image in images:
  5. with open(image, 'rb') as file:
  6. img = Image.open(file)
  7. pixels = list(img.getdata()) # 获取像素数据,以扁平序列表示
  8. black_thresh = (50, 50, 50)
  9. nblack = 0
  10. for pixel in pixels:
  11. if pixel < black_thresh:
  12. nblack += 1
  13. n = len(pixels)
  14. if (nblack / float(n)) > 0.5:
  15. 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:

  1. from PIL import Image
  2. import glob
  3. images = glob.glob(&#39;/content/drive/MyDrive/cropped_images/*.png&#39;) #find all filenames specified by pattern
  4. for image in images:
  5. with open(image, &#39;rb&#39;) as file:
  6. img = Image.open(file)
  7. pixels = list(img.getdata()) # get the pixels as a flattened sequence
  8. black_thresh = (50,50,50)
  9. nblack = 0
  10. for pixel in pixels:
  11. if pixel &lt; black_thresh:
  12. nblack += 1
  13. n = len(pixels)
  14. if (nblack / float(n)) &gt; 0.5:
  15. 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:

确定