英文:
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('/content/drive/MyDrive/cropped_images/*.png') #find all filenames specified by pattern
for image in images:
with open(image, 'rb') 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 < black_thresh:
nblack += 1
n = len(pixels)
if (nblack / float(n)) > 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论