[英]Why are colour pixels detected in .png format images but not in those in .jpg format?
I have a picture with a white background in which there are red, green and blue lines.我有一张白色背景的图片,其中有红色、绿色和蓝色线条。 The red green and blue lines are exclusively of the following values: (255,0,0), (0,255,0) and (0,0,255).
红绿线和蓝线仅具有以下值:(255,0,0)、(0,255,0) 和 (0,0,255)。 The image is now saved as.png and as.jpg.
图像现在保存为 .png 和 as.jpg。 The code should work in both formats.
代码应该以两种格式工作。 The following code is to detect the colours and return the number of the respective colour pixels.
以下代码用于检测颜色并返回相应颜色像素的数量。 As.png the code works, as.jpg only the green pixels are recognised, but unfortunately not all of them.
As.png 代码有效, as.jpg 只有绿色像素被识别,但不幸的是不是全部。 How can all pixels of all 3 colours also be recognised with.jpg?
如何使用.jpg 也能识别所有 3 种颜色的所有像素?
import cv2
import numpy as np
img = cv2.imread(r"...\red.jpg")
x,y,z = img.shape
print(x,y,z)
r = np.where((img == (0, 0, 255)).all(axis=2))
redarray = np.array(r)
red = np.size(redarray)
g = np.where((img == (0, 255, 0)).all(axis=2))
greenarray = np.array(g)
green = np.size(greenarray)
bl = np.where((img == (255, 0, 0)).all(axis=2))
bluearray = np.array(bl)
blue = np.size(bluearray)
print("red: ", red)
print("green: ", green)
print("blue: ", blue)
Without seeing the images, jpeg images are compressed and if not handled with care pixel values are not the same as the equivalent png image.在没有看到图像的情况下,jpeg 图像被压缩,如果不小心处理,像素值与等效的 png 图像不同。
Two approaches:两种方法:
red == (0, 0, 255)
), look for pixels under some thresholds.red == (0, 0, 255)
),不如寻找低于某些阈值的像素。 For example define th=10
and look for red pixels in the range of: green <= 0+th & blue <= 0+th & red >= 255-th
.th=10
并在以下范围内查找红色像素: green <= 0+th & blue <= 0+th & red >= 255-th
。 Sorry I don't have a running code under this answer, let me know if you need further assistance with the masking.抱歉,我在此答案下没有运行代码,如果您需要有关屏蔽的进一步帮助,请告诉我。
The png is lossless format while the jpg is not ( even if you use quality of 100 ). png 是无损格式,而 jpg不是(即使您使用 100 质量)。
This is why part of your original "pure" pixels become "impure" after being saved and reread from jpeg format.这就是为什么部分原始“纯”像素在从 jpeg 格式保存和重新读取后变成“不纯”的原因。
BTW, your question states:顺便说一句,你的问题是:
The red green and blue lines are exclusively of the following values: (255,0,0), (0,255,0) and (0,0,255)
红绿线和蓝线仅具有以下值:(255,0,0)、(0,255,0) 和 (0,0,255)
but the opencv behaviour as well as your code is BGR.但是 opencv 行为以及您的代码是 BGR。 so red, for example is (0,0,255)
如此红色,例如是 (0,0,255)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.