简体   繁体   English

Python在JPEG图像上找到黑色正方形的坐标

[英]Python find the coordinates of black square on JPEG image

I have this sample image that has white rectangular box with a single black square in it . 我有一个示例图像,其中带有白色矩形框,其中有一个黑色正方形 (2 blue arrows are just for illustration purpose, they are not part of the image) (2个蓝色箭头仅用于说明目的,它们不是图像的一部分)

在此处输入图片说明

Is there anyway to find out how many pixels is the black square away from the left and top boundaries of the image? 无论如何,有没有找出黑色正方形距图像的左边界和顶边界有多少像素?

If possible, i prefer not to use OpenCV as the rest of the processing were done in PIL and it's probably an overkill if i have to use OpenCV just to do this one operation. 如果可能的话,我宁愿不使用OpenCV因为其余的处理都是在PIL中完成的,如果我必须仅使用OpenCV来完成这一操作,那可能就太过分了。

FYI: the image is in JPEG, there will always be only 1 black squre (no multiple squares) in the box. 仅供参考:图片为JPEG,框中始终只有1个黑色正方形(没有多个正方形)。

UPDATE UPDATE

Based on the answer by karlphillip, i have come up with this piece of code. 根据karlphillip的回答,我提出了这段代码。

from PIL import Image

img = Image.open('test.png').convert('1')
pixels = img.load()

xlist = []
ylist = []
for y in xrange(img.size[1]):
    for x in xrange(img.size[0]):
        if pixels[x, y] == 0:
            xlist.append(x)
            ylist.append(y)

#4 corners of the black square
xleft = min(xlist)
xright = max(xlist)
ytop = min(ylist)
ybot = max(ylist)

Based on that link I mentioned, I was able to put together the following pseudocode: 根据我提到的链接 ,我可以将以下伪代码放在一起:

from PIL import Image

img = Image.open('test.png')
pixels = img.load()

for y in xrange(img.size[1]):
    for x in xrange(img.size[0]):
        if pixels[x, y] == (0, 0, 0):
            // black pixel found, add it to a counter variable or something.

This answer demonstrates how to access and test each pixel in the image using PIL. 该答案说明了如何使用PIL访问和测试图像中的每个像素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM