Exemplo n.º 1
0
def bgExtract(path):
    img = cv2.imread(path, 1)
    colors, pixel_count = extcolors.extract(path)
    # print(path)
    normPercentages = []
    pieColor = []
    colorLabels = []

    for i in range(len(colors)):
        # keep here the rgb code of the color
        colorRGB = str(colors[i][0])
        colorLabels.append(colorRGB)
#       calculate the percentage of the rgb color in the picture
        percentage = colors[i][1]/pixel_count * 100
        # format the percentage and put it in the matrix of the original percentages
        colorPercentage = '{0:.3f}'.format(percentage)
        normPercentages.append(colorPercentage)

        # We normalize some small values so that they appear correclty in the pie chart
        if percentage <= 0.01:
            percentage = percentage*300
            # print("IN IF ---- with % ",percentage)
        elif percentage <= 0.1:
            percentage = percentage*30
            # print("elif ---- with % ",percentage)
        elif percentage <= 0.5:
            percentage = percentage *10

        # We enter those corrected percentages in the list of the pie chart sizes(how big is each chunk)
        pieColor.append(percentage)
        colorPercentage = '{0:.3f}'.format(percentage)
        # print(colorRGB + ": " + colorPercentage)

    # create the pie chart
    plt.figure()
    patches,texts = plt.pie(pieColor,labels=normPercentages)

    plt.legend(patches, colorLabels, loc="best")

    cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    canny = cv2.Canny(img, 100, 200)
    cv2.imshow(path, canny)

    contours,hierarchy = cv2.findContours(canny,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    if len(contours) > 0:
        cnt = contours[0]
        area = cv2.contourArea(cnt)
        print(area)
        print("\n")

    return area
Exemplo n.º 2
0
 def click_image(self):
     now = datetime.now()
     dt_string = now.strftime("%d%m%Y%H%M%S")
     camera = cv2.VideoCapture(0)
     return_value, image = camera.read()
     cv2.imwrite('./Images/opencv' + dt_string + '.png', image)
     cv2.imwrite('./Images/default.jpg', image)
     del camera
     img = cv2.imread('./Images/opencv' + dt_string + '.png')
     img = cv2.resize(img, (0, 0), fx=0.25, fy=0.25)
     cv2.imwrite('./Images/opencv' + dt_string + '.png', img)
     colors, pixel_count = extcolors.extract('./Images/opencv' + dt_string +
                                             '.png')
     return np.array([[(colors[0])[0][0]], [(colors[0])[0][1]],
                      [(colors[0])[0][2]]])
    def canculateColor(self, img_url):
        image_name = md5(img_url.lower().encode('utf-8')).hexdigest()
        ext = img_url.split(".")
        if ext:
            ext = ext[-1]
        else:
            ext = 'jpg'

        img_filepath = image_name + "." + ext
        logging.info("Downloading image...")
        with open(img_filepath, 'wb') as f:
            f.write(requests.get(img_url).content)

        logging.info("Analyse image color...")
        import extcolors
        if os.path.isfile(img_filepath):
            colors, pixel_count = extcolors.extract(img_filepath)
            os.remove(img_filepath)

            return ','.join(str(color) for color in colors[:5])

        return ''
Exemplo n.º 4
0
def ext_colors(img_path):
    # Renkler ve piksel sayılarının ataması
    colors, pixel_count = extcolors.extract(img_path)

    # Renklerin RGB değerleri ve piksel sayıları
    for i in range(len(colors)):
        print(colors[i])
    print('pixel_count:', pixel_count)
    print()
    print('-----returns as RGB-----')

    # Renklerin metin çıktısı
    i = 0
    while i < len(colors):
        print(
            str(colors[i][0]) + ': %' +
            str(round(((colors[i][1]) / pixel_count) * 100.0, 2)))
        i += 1

    # Renklerin görsel çıktısı
    extcolors.image_result(colors, 100, img_path)
    return colors
Exemplo n.º 5
0
def coloriser(filename):
	colors, pixel_count = extcolors.extract(filename)
	rgb=[]
	for item in colors:
		rgb.append(item[0])
	color1 = []
	for item in rgb:
		color1.append(colorpredictor.get_colour_name(item))
	filtered_colors = set(color1)
	colors_sorted=filtercolors(list(filtered_colors))
	final = set(colors_sorted)
	final = list(final)	
	row = []
	filename_sorted = str(filename).split('/')
	row.append(filename_sorted[-1])
	for i in range(8):
		row.append("0")
	for items in final:
		if items == "red":
			row[1] = "1"
		if items == "blue":
			row[2] = "1"
		if items == "green":
			row[3] = "1"
		if items == "white":
			row[4] = "1"
		if items == "pink":
			row[5] = "1"
		if items == "orange":
			row[6] = "1"
		if items == "yellow":
			row[7] = "1"
		if items == "purple":
			row[8] = "1"
	with open('onehotencoded.csv', 'a') as csvFile:
    		writer = csv.writer(csvFile)
    		writer.writerow(row)
	csvFile.close()
Exemplo n.º 6
0
import os
import cv2
from PIL import Image
import extcolors as ji
"""Save a screenshot from spotify.com in current directory"""
chromedriver = "C:/Users/Siddh/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
driver.get(
    'https://www.incois.gov.in/portal/osf/osfCoastal.jsp?region=coastal&area=westbengal&param=swh&ln=en'
)
screenshot = driver.save_screenshot("my_screenshot1.png")
driver.quit()

im = Image.open('my_screenshot1.png')

outfile = "result.jpg"

region = im.crop((500, 350, 900, 900))
region.save(outfile, "png")
colors, pixel_count = ji.extract(outfile)
for x in colors:
    if ((x[0][0] == 246 and x[0][1] == 157 and x[0][2] == 73)
            or (x[0][0] == 213 and x[0][1] == 254 and x[0][2] == 160)
            or (x[0][0] == 249 and x[0][1] == 219 and x[0][2] == 105)
            or (x[0][0] == 247 and x[0][1] == 220 and x[0][2] == 105)):
        print('alert there')
    else:
        print('No Alert!')
        break
Exemplo n.º 7
0
from functions.EnhanceImage import enhancing
from sklearn.cluster import KMeans
from functions.crop_func import crop
from scipy import ndimage
from functions.func import dist, crop, enhancing, dist1, dist2
import colorgram
################################################
####
name_nat = 'm16.jpg'
name =  'input/'+name_nat
imag = cv2.imread(name)
imag1 = crop(imag)
img =  cv2.cvtColor(imag1, cv2.COLOR_BGR2RGB)
plt.imshow(img)
plt.show()
colors, pixel_count = extcolors.extract(name)
color_group, n = np.shape(colors)
color_centre = np.zeros([color_group,3])
for i in range(0,color_group):
    color_centre[i,0] = colors[i][0][0]
    color_centre[i,1] = colors[i][0][1]
    color_centre[i,2] = colors[i][0][2]
######################################
colorsG = colorgram.extract(name, color_group)
color_centre1 = np.zeros([color_group,3])
for i in range(0,color_group):
    a = colorsG[i]
    color_centre1[i,0] = a.rgb.r
    color_centre1[i,1] = a.rgb.g
    color_centre1[i,2] = a.rgb.b
img21 = np.zeros([img.shape[0] , img.shape[1]])
Exemplo n.º 8
0
def FrameCapture(path):
    # Path to video file
    vidObj = cv2.VideoCapture(path)

    # Used as counter variable
    time.sleep(5)
    count = 0

    # checks whether frames were extracted
    success = 1
    flg = 0
    while success:
        # vidObj object calls read
        # function extract frames
        image: object
        success, image = vidObj.read()

        # Saves the frames with frame-count
        frameoriginal = "originalframe%d.jpg" % count
        cv2.imwrite(frameoriginal, image)

        # im_resized = cv2.resize(image, (224, 224), interpolation=cv2.INTER_LINEAR)
        #cv2.imshow('dst_rt', image)
        #image = Image.open("frame%d.jpg" % count, image)
        #image.show()

        #img = np.zeros((46341, 46341))
        #image = cv2.resize(image, (0, 0), fx=1, fy=61, interpolation=cv2.INTER_CUBIC)
        """image_obj = Image.open("image")
        cropped_image = image_obj.crop(coords)
        cv2.imwrite("frame%d.jpg" % count, image)"""
        crop(frameoriginal, (206, 4, 890, 1079),
             "frameASHWAMEDHA%d.jpg" % count)
        # cropped_image.save(saved_location)
        #cropped_image.show()
        """colors, pixel_count = ji.extract("frameASHWAMEDHA%d.jpg" % count)
        print(colors)"""
        frameoriginalextract = "frameASHWAMEDHA%d.jpg" % count
        colors, pixel_count = ji.extract(frameoriginalextract)
        # print(colors)
        for x in colors:
            """print(x[0][0])
            print(x[0][1])
            print(x[0][2])"""
            if ((x[0][0] == 246 and x[0][1] == 157 and x[0][2] == 73)
                    or (x[0][0] == 213 and x[0][1] == 254 and x[0][2] == 160)
                    or (x[0][0] == 249 and x[0][1] == 219 and x[0][2] == 105)
                    or (x[0][0] == 247 and x[0][1] == 220 and x[0][2] == 105)):
                print('alert there')
                #sending Email alerts to everyone

                content = 'TSUNAMI ALERT!!!!'
                mail = smtplib.SMTP('smtp.gmail.com', 587)
                mail.ehlo()
                mail.starttls()
                recipients = [
                    '*****@*****.**', '*****@*****.**',
                    '*****@*****.**', '*****@*****.**'
                ]
                mail.login('*****@*****.**', 'sk27$9806')
                mail.sendmail('*****@*****.**', recipients, content)
                mail.close()

                firebase.database().child("RealTime Node").child("Mane").set(
                    "5")
                #Updating the Database
                #sending text messages

                frameoriginalextract.show()
                flg = 1
                break
        count += 1
        if flg == 1:
            break
Exemplo n.º 9
0
    f.close()
print(flist)
print(len(flist))
print(flist1)
# np.save('train_data.npy', training_data)
# return training_data

j = 0
for i in range(0, 90):
    d = str(flist[j])
    e = "/home/ananth/images/" + d
    print(e)
    img = cv2.imread(e, 1)
    icrop = img[1500:1500 + 500, 2000:2000 + 500]
    cv2.imwrite("r.jpg", icrop)
    colors, pixel_count = extcolors.extract("r.jpg")
    print(colors)
    j = j + 1

    if colors[2][0] is None:
        continue
    meanr = (colors[0][0][0] * colors[0][1] + colors[1][0][0] * colors[1][1] +
             colors[2][0][0] * colors[2][1]) / (colors[0][1] + colors[1][1] +
                                                colors[2][1])
    meang = (colors[0][0][1] * colors[0][1] + colors[1][0][1] * colors[1][1] +
             colors[2][0][1] * colors[2][1]) / (colors[0][1] + colors[1][1] +
                                                colors[2][1])
    meanb = (colors[0][0][2] * colors[0][1] + colors[1][0][2] * colors[1][1] +
             colors[2][0][2] * colors[2][1]) / (colors[0][1] + colors[1][1] +
                                                colors[2][1])
    row = [
Exemplo n.º 10
0
    # # define criteria, number of clusters(K) and apply kmeans()
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
    K = 8
    ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

    # # Now convert back into uint8, and make original image
    center = np.uint8(center)
    res = center[label.flatten()]
    res2 = res.reshape((img.shape))
    new_img_dir = join('Kmeans_MOMA',img_dir.split('/')[1])
    cv2.imwrite(new_img_dir,res2)
    
    #save the compressed image 
    
    colors,pixel_count = extcolors.extract(path = new_img_dir,tolerance=10)
    colors = [list(f) for f in colors]
#     print(colors)
    channel = min(8,len(colors))
    dominant_color = colors[:channel]
    max_color=colors[0][0]
#     print(dominant_color)
    sum_pixel = sum([x[1] for x in dominant_color])
    for sub in dominant_color:
        sub[1] = sub[1]/sum_pixel
    item['Domain color'] = dominant_color
    item['Max Color']= max_color
    newjson.append(item)
    count = count+1
    
    if count %100 ==0:
import extcolors as ji
colors, pixel_count = ji.extract("ak.gif")
print(colors)
print(pixel_count)
print((colors[0]))
print((colors[0][0]))
print((colors[0][0][0]))

#5*2 banner
#4*3 standee

#255 124 124 - last Fourth 3.9-4.2
#255 160 69  - last sixth  3.3-3.6
def FrameCapture(path):
    # Path to video file
    vidObj = cv2.VideoCapture(path)

    # Used as counter variable
    time.sleep(5)
    count = 0

    # checks whether frames were extracted
    success = 1
    flg = 0
    while success:
        # vidObj object calls read
        # function extract frames
        image: object
        success, image = vidObj.read()

        # Saves the frames with frame-count
        frameoriginal = "originalframe%d.jpg" % count
        cv2.imwrite(frameoriginal, image)

        # im_resized = cv2.resize(image, (224, 224), interpolation=cv2.INTER_LINEAR)
        #cv2.imshow('dst_rt', image)
        #image = Image.open("frame%d.jpg" % count, image)
        #image.show()

        #img = np.zeros((46341, 46341))
        #image = cv2.resize(image, (0, 0), fx=1, fy=61, interpolation=cv2.INTER_CUBIC)
        """image_obj = Image.open("image")
        cropped_image = image_obj.crop(coords)
        cv2.imwrite("frame%d.jpg" % count, image)"""
        crop(frameoriginal, (206, 4, 890, 1079),
             "frameASHWAMEDHA%d.jpg" % count)
        # cropped_image.save(saved_location)
        #cropped_image.show()
        """colors, pixel_count = ji.extract("frameASHWAMEDHA%d.jpg" % count)
        print(colors)"""
        frameoriginalextract = "frameASHWAMEDHA%d.jpg" % count
        colors, pixel_count = ji.extract(frameoriginalextract)
        # print(colors)
        for x in colors:
            """print(x[0][0])
            print(x[0][1])
            print(x[0][2])"""
            if ((x[0][0] == 246 and x[0][1] == 157 and x[0][2] == 73)
                    or (x[0][0] == 213 and x[0][1] == 254 and x[0][2] == 160)
                    or (x[0][0] == 249 and x[0][1] == 219 and x[0][2] == 105)
                    or (x[0][0] == 247 and x[0][1] == 220 and x[0][2] == 105)):
                print('alert there')
                #sending Email alerts to everyone
                nvar = "1"
                firebase.database().child("RealTime Node").child("Mane").set(
                    nvar)  #Updating the Database

                dlink = firebase.database().child("Images").child(
                    nvar).get().val()
                #dlink="https://firebasestorage.googleapis.com/v0/b/test-3f09a.appspot.com/o/1.jpg?alt=media&token=9cf380b8-755a-4723-8d41-4cd98c5e8f58"

                content = 'TSUNAMI ALERT!!!!' + '\nThe Safe zones are as follows: ' + dlink
                mail = smtplib.SMTP('smtp.gmail.com', 587)
                mail.ehlo()
                mail.starttls()
                recipients = [
                    '*****@*****.**', '*****@*****.**',
                    '*****@*****.**', '*****@*****.**'
                ]
                mail.login('*****@*****.**', 'sk27$9806')
                mail.sendmail('*****@*****.**', recipients, content)
                mail.close()

                #sending text messages

                account_sid = 'ACbb713e5387b4d4d93ecd8c7b80cf6cfb'
                auth_token = '72a40562f8b77477f06c52a1f5e19855'
                client = Client(account_sid, auth_token)

                message = client.messages.create(
                    body="Tsunami Alert!!" +
                    '\nFollowing are the safe zones you should head  to :' +
                    dlink,
                    from_='+19497634689',
                    to='+919881862818')

                print(message.sid)

                # Your Account Sid and Auth Token from twilio.com/console
                account_sid = 'AC42f06897050e484f5624419e1701f0db'
                auth_token = '4e52319b8760b0a2743ecbbfbefccab0'
                client = Client(account_sid, auth_token)

                message = client.messages.create(
                    body="Tsunami Alert!!" +
                    '\nFollowing are the safe zones you should head  to :' +
                    dlink,
                    from_='+16106869128',
                    to='+919421986210')

                print(message.sid)

                account_sid = 'AC0fe52979971e508c946069aaf822499e'
                auth_token = '1a5f643116b1d884ab5e0d8fadd80f9b'
                client = Client(account_sid, auth_token)

                message = client.messages.create(
                    body="Tsunami Alert!!" +
                    '\nFollowing are the safe zones you should head  to :' +
                    dlink,
                    from_='+19284517433',
                    to='+918007817047')

                print(message.sid)

                account_sid = 'AC4106d85131931e833b4ae54621c0375b'
                auth_token = '89ac03a76fe7e425b2444c3c47333e15'
                client = Client(account_sid, auth_token)

                message = client.messages.create(
                    body="Tsunami Alert!!" +
                    '\nFollowing are the safe zones you should head  to :' +
                    dlink,
                    from_='+13216168741',
                    to='+919637336606')

                print(message.sid)

                account_sid = 'ACbb713e5387b4d4d93ecd8c7b80cf6cfb'
                auth_token = '72a40562f8b77477f06c52a1f5e19855'
                client = Client(account_sid, auth_token)

                message = client.messages.create(
                    body="Tsunami Alert!!" +
                    '\nFollowing are the safe zones you should head  to :' +
                    dlink,
                    from_='+19497634689',
                    to='+919881862818')

                print(message.sid)

                # Your Account Sid and Auth Token from twilio.com/console
                account_sid = 'AC42f06897050e484f5624419e1701f0db'
                auth_token = '4e52319b8760b0a2743ecbbfbefccab0'
                client = Client(account_sid, auth_token)

                message = client.messages.create(
                    body="Tsunami Alert!!" +
                    '\nFollowing are the safe zones you should head  to :' +
                    dlink,
                    from_='+16106869128',
                    to='+919421986210')

                print(message.sid)

                account_sid = 'AC0fe52979971e508c946069aaf822499e'
                auth_token = '1a5f643116b1d884ab5e0d8fadd80f9b'
                client = Client(account_sid, auth_token)

                message = client.messages.create(
                    body="Tsunami Alert!!" +
                    '\nFollowing are the safe zones you should head  to :' +
                    dlink,
                    from_='+19284517433',
                    to='+918007817047')

                print(message.sid)

                account_sid = 'AC537a49d120b9fa65e37ccc04b9b37b10'
                auth_token = '1706d481924a04924a35eb0b76afb3f8'
                client = Client(account_sid, auth_token)

                message = client.messages.create(
                    body="Tsunami Alert!!" +
                    '\nFollowing are the safe zones you should head  to :' +
                    dlink,
                    from_='+12015281649',
                    to='+919518371149')

                print(message.sid)

                frameoriginalextract.show()
                flg = 1
                break
        count += 1
        if flg == 1:
            break
Exemplo n.º 13
0
import extcolors
#IMAGINI NORMALE
colorsn1, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/n1.jpg")
colorsn2, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/n2.jpg")
colorsn3, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/n3.jpg")
colorsn4, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/n4.jpg")
colorsn5, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/n5.jpg")
colorsn6, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/n6.jpg")
colorsn7, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/n7.jpg")
colorsn8, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/n9.jpg")
colorsn9, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/n10.jpg")



colorss1, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/s1.jpg")
colorss2, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/s2.jpg")
colorss3, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/s3.jpg")
colorss4, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/s4.jpg")
colorss5, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/s5.jpg")
colorss6, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/s6.jpg")
colorss7, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/s7.jpg")
colorss8, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/s8.jpg")
colorss9, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/s9.jpg")
colorss10, pixel_count = extcolors.extract("C:/Users/PycharmProjects/LAB10/Imagini/s10.jpg")

def averageRed(colors): #
    x=0
    s=0
    for i in range(0,min(5,len(colors))):
        for j in range(0,3):
            s = s + colors[i][0][j]