簡體   English   中英

着色連續的像素集

[英]Coloring Continuous set of Pixels

我有一個使用 OpenCV 用 python 編寫的程序,我正在嘗試為一組像素着色。 條件是,如果有超過 1000 個連續像素,那么所有這 1000 個像素必須用不同的顏色着色,對於本例,該顏色為紅色。

編碼:

import cv2
import numpy as np

print("Package Imported")

coordinate = x, y = 150, 69
imgColor = cv2.imread(r"D:\Downloads\residence-g1678df24f_1280.jpg")
img = cv2.imread(
    r"D:\Downloads\residence-g1678df24f_1280.jpg", 0)
res, img2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

l = len(img2)
w = len(img2[0])
print(l, w)
count = 1

y=0
x=0
sX=0
sY=0
for x in range(0,l):
    imgColor[0,x]=(0,0,255)
    for y in range(0,w):

        if img2[x,y]==255:
            count=count+1
        else:
            count=1
            sX = x
            sY = y
            print(img2[x,y],x,y)

        if count > 1000:
            print("Coloring from ", sX, sY, "to ", x, y)
            for i in range(sX, x):
                for j in range(sY, y):
                    imgColor[i, j] = (0, 0, 255)
                    count=1

cv2.imshow("GrayScale Image", img)
cv2.imshow("Photo", img2)
cv2.imshow("Color Image", imgColor)
cv2.imwrite("D:/VS Projects/openCVTEST/ColoredImage.jpg", imgColor)
cv2.imwrite("D:/VS Projects/openCVTEST/ThresholdImage.jpg", img2)
cv2.imwrite("D:/VS Projects/openCVTEST/GrayScaleImage.jpg",img)
cv2.waitKey(0)

基本上,我首先對圖像進行threshold處理,然后使用if運算符檢查當前像素是否為白色。 如果像素是白色的,那么變量count會增加。 如果不是,則將count重置為 0,並將sXsY標記為起始坐標。 一旦count超過 1000,就會運行另一個for循環,將(sX,sY) imgColor imgColor 着色為當前像素(x,y)

但是,我得到的結果是這樣的:

圖像顏色:

在此處輸入圖像描述

img2(閾值):

在此處輸入圖像描述

img(灰度): 在此處輸入圖像描述

理想情況下,更多的空白區域(例如房子左邊的空白區域)不應該也被塗成紅色嗎? 由於thresholded圖像只有2550 ,因此255中的更多也應該是red的。 我的邏輯本身是錯誤的,還是我遺漏了什么? 我將最小計數(count > 100)更改為 100,但即使這樣也會產生類似的結果。

如果你想達到這個效果,可以繼續看我下面的示例代碼

提示:我使用的是你的染色圖像,所以圖像右上角的天空會受到染色的影響

一世

import cv2

# read the picture
img_color = cv2.imread(r"C:\Users\SY\Desktop\test\A.jpg", 1)
img_gray = cv2.imread(r"C:\Users\SY\Desktop\test\A.jpg", 0)
# get img_hight and img_width
img_hight = len(img_color)
img_width = len(img_color[0])

# use the key to change the result
threshold_key = 150
img_gray = cv2.threshold(img_gray, threshold_key, 255, cv2.THRESH_BINARY)[1]

color_one = (0,0,255)
for hight in range(0, img_hight):
    flag_width = 0
    for width in range(0, img_width):
        if img_gray[hight, width] == 0:  
            if width - flag_width  > 200 :
                for w in range(flag_width, width):
                    img_color[hight, w] = color_one
            flag_width = width
        
        # if the whole line is whithe
        if (width == img_width-1) and (flag_width == 0) :
            for w in range(width+1): 
                img_color[hight, w] = color_one
cv2.imwrite("A.bmp", img_color)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM